#!/usr/bin/env bash
##############
if [[ $(command -v dpkg) && $(command -v apt-get) ]]; then
    DPKG_ARCH=$(dpkg --print-architecture)
    case ${DPKG_ARCH} in
    armel) ARCH_TYPE="armel" ;;
    armv7* | armv8l | armhf | arm) ARCH_TYPE="armhf" ;;
    aarch64 | arm64* | armv8* | arm*) ARCH_TYPE="arm64" ;;
    i*86 | x86) ARCH_TYPE="i386" ;;
    x86_64 | amd64) ARCH_TYPE="amd64" ;;
    *) ARCH_TYPE=${DPKG_ARCH} ;;
    esac
else
    #ARM7：ARMv4，ARM9：ARMv5，ARM11：ARMv6，ARM-Cortex：ARMv7
    UNAME_ARCH=$(uname -m)
    case ${UNAME_ARCH} in
    armv7* | armv8l) ARCH_TYPE="armhf" ;;
    armv[1-6]*) ARCH_TYPE="armel" ;;
    aarch64 | armv8* | arm64 | arm*) ARCH_TYPE="arm64" ;;
    x86_64 | amd64) ARCH_TYPE="amd64" ;;
    i*86 | x86) ARCH_TYPE="i386" ;;
    s390*) ARCH_TYPE="s390x" ;;    #经测试uname -m输出的结果为s390x
    ppc64*) ARCH_TYPE="ppc64el" ;; #经测试uname -m输出的结果为ppc64le，而不是ppc64el
    mips64*) ARCH_TYPE="mips64el" ;;
    mips*) ARCH_TYPE="mipsel" ;; #经测试uname -m输出的结果为mips，而不是mipsel
    riscv64*) ARCH_TYPE="riscv64" ;;
    *) printf "${RED}%s${RESET} %s ${RED}%s${RESET}\n" "未知的架构" "${UNAME_ARCH}" "unknown architecture" ;;
    esac
fi
TRUE_ARCH_TYPE=${ARCH_TYPE}
GNU_TAR_BIN="$(command -v tar)"
######################
QEMU_ARCH=''
CONFIG_FOLDER="${HOME}/.config/tmoe-linux"
ACROSS_ARCH_FILE="${CONFIG_FOLDER}/across_architecture_container.txt"
if [ -e "${ACROSS_ARCH_FILE}" ]; then
    ARCH_TYPE="$(head -n 1 ${ACROSS_ARCH_FILE})"
    QEMU_ARCH="$(sed -n 2p ${ACROSS_ARCH_FILE})"
fi
LINUX_CONTAINER_DISTRO_FILE="${CONFIG_FOLDER}/linux_container_distro.txt"
LINUX_CONTAINER_DISTRO_FILE_02="${CONFIG_FOLDER}/linux_container_distro_02.txt"
DEBIAN_FOLDER=debian_${ARCH_TYPE}
if [ -e "${LINUX_CONTAINER_DISTRO_FILE}" ]; then
    LINUX_CONTAINER_DISTRO=$(head -n 1 "${LINUX_CONTAINER_DISTRO_FILE}")
    [[ -z "${LINUX_CONTAINER_DISTRO}" ]] || DEBIAN_FOLDER="${LINUX_CONTAINER_DISTRO}_${ARCH_TYPE}"
fi
if [ -e "${LINUX_CONTAINER_DISTRO_FILE_02}" ]; then
    LINUX_CONTAINER_DISTRO_02=$(head -n 1 "${LINUX_CONTAINER_DISTRO_FILE_02}")
fi
if [ -e "${CONFIG_FOLDER}/chroot_container" ]; then
    TMOE_CHROOT=true
    CONTAINER_TYPE='chroot'
    if [ $(command -v sudo) ]; then
        TMOE_CHROOT_PREFIX=sudo
    elif [ $(command -v tsudo) ]; then
        TMOE_CHROOT_PREFIX=tsudo
    fi
    SYSTEMD_NSPAWN=$(grep -E '^[^#]*SYSTEMD_NSPAWN=' "${CONFIG_FOLDER}"/chroot.conf | awk -F '=' '{print $2}')
else
    CONTAINER_TYPE='proot'
    TMOE_CHROOT=false
    TMOE_CHROOT_PREFIX=''
fi
CONTAINER_DISTRO="$(printf "%s\n" "${DEBIAN_FOLDER}" | awk -F '_' '{print $1}' | cut -d '-' -f 1)"
#DEBIAN_FOLDER=debian_arm64
TMOE_LOCALE_FILE="${CONFIG_FOLDER}/locale.txt"
[[ ! -s "${TMOE_LOCALE_FILE}" ]] || TMOE_LANG=$(head -n 1 "${TMOE_LOCALE_FILE}")
RED=$(printf '\033[31m')
GREEN=$(printf '\033[32m')
YELLOW=$(printf '\033[33m')
BLUE=$(printf '\033[34m')
PURPLE=$(printf '\033[35m')
CYAN=$(printf '\033[36m')
RESET=$(printf '\033[m')
BOLD=$(printf '\033[1m')

tmoe_manager_env() {
    TMOE_GIT_DIR="${TMOE_LINUX_DIR}/git"
    TMOE_CONTAINER_DIR="${TMOE_LINUX_DIR}/containers"
    TMOE_TOOL_DIR="${TMOE_GIT_DIR}/share/old-version/tools"
    TMOE_SHARE_DIR="${TMOE_GIT_DIR}/share/old-version/share"
    mkdir -pv "${TMOE_CONTAINER_DIR}"
    case ${TMOE_CHROOT} in
    true) DEBIAN_CHROOT=${TMOE_CONTAINER_DIR}/chroot/${DEBIAN_FOLDER} ;;
    *) DEBIAN_CHROOT=${TMOE_CONTAINER_DIR}/proot/${DEBIAN_FOLDER} ;;
    esac
    TMOE_STARTUP_DIR="${DEBIAN_CHROOT}/usr/local/etc/tmoe-linux/container"
    TMOE_STARTUP_SCRIPT="${TMOE_STARTUP_DIR}/tmoe-linux-container"
    TMOE_NSPAWN_SCRIPT="${TMOE_STARTUP_DIR}/nspawn"
    #${TMOE_CHROOT_PREFIX}
    mkdir -pv "${DEBIAN_CHROOT}" || ${TMOE_CHROOT_PREFIX} mkdir -pv "${DEBIAN_CHROOT}"
    ${TMOE_CHROOT_PREFIX} chmod 755 -v "${DEBIAN_CHROOT}"
    #mkdir -pv ${TMOE_CONTAINER_DIR}
    [[ -n ${TMPDIR} ]] || TMPDIR=/tmp
}
#############
if [ "$(uname -o)" = "Android" ]; then
    LINUX_DISTRO='Android'
    TMOE_LINUX_DIR="${HOME}/.local/share/tmoe-linux"
    tmoe_manager_env
    [[ -L "/data/data/com.termux/files/home/storage/shared" ]] || termux-setup-storage
    TF_CARD_PATH="${HOME}/storage/external-1"
    [ ! -h "${TF_CARD_PATH}" ] || printf "%s\n" "$(readlink ${TF_CARD_PATH})" >"${TF_CARD_PATH}"/path.txt
else
    TMOE_LINUX_DIR="/usr/local/etc/tmoe-linux"
    tmoe_manager_env
    LINUX_DISTRO='linux'
    if grep -Eq "opkg|entware" '/opt/etc/opkg.conf' 2>/dev/null || grep -q 'openwrt' "/etc/os-release"; then
        LINUX_DISTRO='openwrt'
        if [ -d "/opt/bin" ]; then
            PREFIX="/opt"
        else
            PREFIX=${HOME}
        fi
    else
        PREFIX='/usr/local'
        [[ -d ${PREFIX} ]] || PREFIX='/usr'
    fi
    mkdir -pv ${PREFIX}/bin
fi
####################
printf "${YELLOW}"
printf "%s\n" "                                        "
printf "%s\n" "                 .::::..                "
printf "%s\n" "      ::::rrr7QQJi::i:iirijQBBBQB.      "
printf "%s\n" "      BBQBBBQBP. ......:::..1BBBB       "
printf "%s\n" "      .BuPBBBX  .........r.  vBQL  :Y.  "
printf "%s\n" "       rd:iQQ  ..........7L   MB    rr  "
printf "%s\n" "        7biLX .::.:....:.:q.  ri    .   "
printf "%s\n" "         JX1: .r:.r....i.r::...:.  gi5  "
printf "%s\n" "         ..vr .7: 7:. :ii:  v.:iv :BQg  "
printf "%s\n" "         : r:  7r:i7i::ri:DBr..2S       "
printf "%s\n" "      i.:r:. .i:XBBK...  :BP ::jr   .7. "
printf "%s\n" "      r  i....ir r7.         r.J:   u.  "
printf "%s\n" "     :..X: .. .v:           .:.Ji       "
printf "%s\n" "    i. ..i .. .u:.     .   77: si   1Q  "
printf "%s\n" "   ::.. .r .. :P7.r7r..:iLQQJ: rv   ..  "
printf "%s\n" "  7  iK::r  . ii7r LJLrL1r7DPi iJ     r "
printf "%s\n" "    .  ::.:   .  ri 5DZDBg7JR7.:r:   i. "
printf "%s\n" "   .Pi r..r7:     i.:XBRJBY:uU.ii:.  .  "
printf "%s\n" "   QB rJ.:rvDE: .. ri uv . iir.7j r7.   "
printf "%s\n" "  iBg ::.7251QZ. . :.      irr:Iu: r.   "
printf "%s\n" "   QB  .:5.71Si..........  .sr7ivi:U    "
printf "%s\n" "   7BJ .7: i2. ........:..  sJ7Lvr7s    "
printf "%s\n" "    jBBdD. :. ........:r... YB  Bi      "
printf "%s\n" "       :7j1.                 :  :       "
printf "${RESET}"
###########################
TUNA_LXC_IMAGE_MIRROR_REPO="https://mirrors.bfsu.edu.cn/lxc-images/images/debian/sid/${ARCH_TYPE}/default"
TUNA_LXC_IMAGE_MIRROR_REPO_02="https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/debian/sid/${ARCH_TYPE}/default"
TMOE_ROOTFS_TAR_XZ="debian-sid_${ARCH_TYPE}-rootfs.tar.xz"
TMOE_PROOT_PROC_FILE_URL='https://gitee.com/ak2/proot_proc/raw/master/proc.tar.xz'
TMOE_PROOT_PROC_GIT="https://gitee.com/ak2/proot_proc"
TMOE_PROOT_PROC_GIT_02="https://github.com/cu233/proot_proc"
###########
tmoe_tips_1_zh() {
    cat <<-EOF
		少女祈禱中...
		現在可公開的情報:
		${BOLD}Tmoe-linux 小提示${RESET}:
				01:不同远程桌面的体验有可能是不同的呢！ヽ(✿ﾟ▽ﾟ)ノ
				Different remote desktops may have different experiences.
				-------------------
				02:在某种环境下执行某条命令，将同时调用宿主机的VNC viewer和容器的vnc server。
				-------------------
				03:只有最近使用的容器的启动命令才是一样的哦！o( =•ω•= )m
				但是呢！输那条启动命令仅支持启动${BLUE}${DEBIAN_FOLDER}容器${RESET}，不会自动启动远程桌面服务。
				-------------------
				04:并非所有${YELLOW}字体${RESET}都支持${BLUE}powerlevel 10k${RESET}的特殊字符哦！🍥
				Some fonts do not support powerlevel10k special characters.
				-------------------
				输${GREEN}novnc${RESET}启动${BLUE}novnc${RESET},novnc需要使用浏览器来连接。(o゜▽゜)o☆
				You can type ${GREEN}novnc${RESET} to ${YELLOW}start ${BLUE}novnc+websockify${RESET}
				(o゜▽゜)o☆ Open your browser and enjoy it!
				------------------
				检测到您当前的架构为${YELLOW}${ARCH_TYPE}${RESET}，${GREEN}debian container${RESET}将安装至${BLUE}${DEBIAN_CHROOT}${RESET}
	EOF
}
tmoe_tips_1_en() {
    cat <<-EOF
		${BOLD}Tmoe-linux TIPS${RESET}:
				01:Different remote desktops may have different experiences.ヽ(✿ﾟ▽ﾟ)ノ
				-------------------
				02:You can type ${GREEN}debian${RESET} to start ${BLUE}${DEBIAN_FOLDER}${RESET} container. o( =•ω•= )m
				-------------------
				03:Some fonts do not support powerlevel10k special characters.🍥
				-------------------
				04.You can type ${GREEN}novnc${RESET} to ${YELLOW}start ${BLUE}novnc+websockify${RESET}
				(o゜▽゜)o☆ Open your browser and enjoy it!
				Detected that your current architecture is ${YELLOW}${ARCH_TYPE}${RESET}, ${GREEN}debian container${RESET} will be installed to ${BLUE}${DEBIAN_CHROOT}${RESET}
				------------------   
	EOF
}
case ${TMOE_LANG} in
zh_*UTF-8) tmoe_tips_1_zh ;;
*) tmoe_tips_1_en ;;
esac
##################
check_rootfs_dir() {
    unset ROOTFS_DIR
    for i in /sdcard ${HOME}/sd; do
        if [ -d "${i}" ]; then
            ROOTFS_DIR="${i}/Download/backup/rootfs"
            mkdir -pv ${ROOTFS_DIR}
        fi
        break
    done
}
if [ -h "${HOME}/storage/external-1" ]; then
    ROOTFS_DIR=${HOME}/storage/external-1/Download/backup/rootfs
    mkdir -pv ${ROOTFS_DIR}
    if [[ ! -e ${ROOTFS_DIR} ]]; then
        check_rootfs_dir
    fi
else
    check_rootfs_dir
fi

[[ -n ${ROOTFS_DIR} ]] || ROOTFS_DIR="${HOME}/sd/Download/backup/rootfs"

if [[ ! -e ${ROOTFS_DIR} ]]; then
    ROOTFS_DIR="${HOME}/sd/Download/backup/rootfs"
    mkdir -pv ${ROOTFS_DIR}
fi
cd ${ROOTFS_DIR}
CURRENT_TMOE_DIR=$(pwd)
download_rootfs_file() {
    printf "${PURPLE}${BOLD}%s${RESET} ${YELLOW}%s${RESET}\n" "ROOTFS_FILE:" "${ROOTFS_DIR}/${TMOE_ROOTFS_TAR_XZ}"
    if [ ! -f ${TMOE_ROOTFS_TAR_XZ} ]; then
        printf "%s\n" "Downloading ${BLUE}${TMOE_ROOTFS_TAR_XZ}${RESET} from BFSU Open Source Mirror Station."
        case ${WEEKLY_BUILD_CONTAINER} in
        true)
            ROOTFS_URL="${NODE_URL}/${ROOTFS_VERSION}/${ARCH_TYPE}/${LINUX_CONTAINER_DISTRO_02}/${DESKTOP}/${LINUX_CONTAINER_DISTRO_02}_${ARCH_TYPE}-rootfs.tar.zst"
            case ${NODE_NAME} in
            "node02-tmoe") aria2c --console-log-level=error --no-conf -x7 -s7 -k1M --http-user="${NODE02_USER}" --http-passwd="${NODE02_PW}" -o ${TMOE_ROOTFS_TAR_XZ} "${ROOTFS_URL}" || aria2c --console-log-level=debug --max-tries=0 --no-conf --allow-overwrite=true -x3 -s3 -k1M --http-user="${NODE02_USER}" --http-passwd="${NODE02_PW}" -o ${TMOE_ROOTFS_TAR_XZ} "${ROOTFS_URL}" ;;
            *) aria2c --console-log-level=error --no-conf -x6 -s6 -k1M -o ${TMOE_ROOTFS_TAR_XZ} "${ROOTFS_URL}" || aria2c --console-log-level=debug --max-tries=0 --no-conf --allow-overwrite=true -x4 -s4 -k1M -o ${TMOE_ROOTFS_TAR_XZ} "${ROOTFS_URL}" ;;
            esac
            #若下载失败，则重复尝试。
            ;;
        *)
            #printf "%s\n" "正在从${YELLOW}北京外国语大学开源镜像站${RESET}${GREEN}下载${RESET}容器镜像..."
            unset TTIME
            TTIME=$(curl --connect-timeout 10 -L "${TUNA_LXC_IMAGE_MIRROR_REPO}/" | grep date | sed -E 's@<a (href)@\n\1@g' | awk -F 'href=' '{print $2}' | cut -d '"' -f 2 | tail -n 1)
            [[ -n ${TTIME} ]] || TTIME=$(curl -Lv "${TUNA_LXC_IMAGE_MIRROR_REPO_02}/" | grep date | sed -E 's@<a (href)@\n\1@g' | awk -F 'href=' '{print $2}' | cut -d '"' -f 2 | tail -n 1)
            #printf "${YELLOW}%s${RESET}\n" "${TUNA_LXC_IMAGE_MIRROR_REPO}/${TTIME}rootfs.tar.xz"
            aria2c --console-log-level=warn --connect-timeout=10 --no-conf -x 5 -k 1M --split 5 -o ${TMOE_ROOTFS_TAR_XZ} "${TUNA_LXC_IMAGE_MIRROR_REPO}/${TTIME}rootfs.tar.xz" || aria2c --console-log-level=debug --max-tries=0 --no-conf -x 5 -k 1M --split 5 -o ${TMOE_ROOTFS_TAR_XZ} "${TUNA_LXC_IMAGE_MIRROR_REPO_02}/${TTIME}rootfs.tar.xz"
            ;;
        esac
    fi
}
DEBOOTSTRAP_DIR=''
[[ ! -e ${CONFIG_FOLDER}/debootstrap_dir.txt ]] || source ${CONFIG_FOLDER}/debootstrap_dir.txt
case ${DEBOOTSTRAP_DIR} in
${DEBIAN_CHROOT}) ;;
*) download_rootfs_file ;;
esac
##################
if [ ! -e "${CONFIG_FOLDER}/chroot_container" ]; then
    cd ${CONFIG_FOLDER}
    if [ ! -s "proot_proc/proc.tar.xz" ]; then
        [[ ! -e proot_proc ]] || rm -rfv proot_proc
        git clone \
            --depth=1 \
            ${TMOE_PROOT_PROC_GIT} \
            proot_proc ||
            git clone \
                --depth=1 \
                ${TMOE_PROOT_PROC_GIT_02} \
                proot_proc
    fi
    if [ ! -s "proot_proc/proc.tar.xz" ]; then
        mkdir -pv proot_proc
        aria2c --console-log-level=warn --no-conf -d proot_proc -o proc.tar.xz --allow-overwrite=true "${TMOE_PROOT_PROC_FILE_URL}"
    fi
    cd ${DEBIAN_CHROOT}
    if [ -e "${CONFIG_FOLDER}/proot_proc/proc.tar.xz" ]; then
        ${GNU_TAR_BIN} -Jxf ${CONFIG_FOLDER}/proot_proc/proc.tar.xz 2>/dev/null
    fi
else
    cd ${DEBIAN_CHROOT}
fi
####################
printf "$BLUE"
cat <<-'EndOFneko'
	       DL.                           
	       QBBBBBKv:rr77ri:.             
	       gBBQdY7::::..::i7vv.          
	       UBd. . .:.........rBBBQBBBB5  
	       Pu  :..r......i:....BBBQBBB:  
	       ri.i:.j:...:. i7... uBBZrd:   
	 :     7.:7.7U.:..r: Yr:.. iQ1:qU    
	.Qi   .7.ii.X7:...L.:qr:...iB7ZQ     
	 .27. :r.r:L7i::.7r:vri:...rr  .     
	  v   ::.Yrviri:7v7v: ::...i.   i    
	      r:ir: r.iiiir..:7r...r   :P.2Y 
	      v:vi::.      :  ::. .qI7U1U :1 
	Qr    7.7.         :.i::. :Di:. i .v:
	v7..  s.r7.   ...   .:7i: rDi...r .. 
	 vi: .7.iDBBr  .r   .:.7. rPr:..r    
	 i   :virZBgi  :vrYJ1vYY .ruY:..i    
	     YrivEv. 7BBRBqj21I7 .77J:.:.PQ  
	    .1r:q.   rB52SKrj.:i i5isi.:i :.r
	    YvrY7    r.  . ru :: PIrj7.:r..v 
	   rSviYI..iuU .:.:i:.7.KPPiSr.:vr   
	  .u:Y:JQMSsJUv...   .rDE1P71:.7X7   
	  5  Ivr:QJ7JYvi....ir1dq vYv.7L.Y   
	  S  7Z  Qvr:.iK55SqS1PX  Xq7u2 :7   
	         .            i   7          
EndOFneko
printf "$RESET"
LONG_DISTRO_NAME=$(printf '%s\n' "${LINUX_CONTAINER_DISTRO}" | awk -F '-' '{print $1}' | cut -d '_' -f 1)
LONG_DISTRO_CODE=$(printf '%s\n' "${LINUX_CONTAINER_DISTRO}" | awk -F '-' '{print $2}')
[[ ! $(printf '%s\n' "${LINUX_CONTAINER_DISTRO}" | awk -F '-' '{print $3}') = Stream ]] || LONG_DISTRO_CODE=$(printf '%s\n' "${LINUX_CONTAINER_DISTRO}" | awk -F '-' '{print $2"-"$3}')
LONG_DISTRO_ARCH=${ARCH_TYPE}
tmoe_tips_2_zh() {
    cat <<-EOF
		現在可公開的情報:
		${BOLD}Tmoe-linux 小提示05${RESET}(仅适用于GUI安装完成后):
				输${GREEN}startx11vnc${RESET}启动${BLUE}x11vnc服务${RESET},x11vnc能运行tightvnc无法打开的某些应用哦！
				-------------------
				You can type ${GREEN}startx11vnc${RESET} to ${YELLOW}start ${BLUE}x11vnc server.${RESET}
				------------------
				若您的宿主机为${BOLD}Android${RESET}系统,则在termux原系统下输${GREEN}startvnc${RESET}将${RED}同时启动${RESET}安卓版Realvnc${YELLOW}客户端${RESET}和${BOLD}${DEBIAN_FOLDER}${RESET}的${BLUE}VNC服务端${RESET}。
				------------------
				输${GREEN}startxsdl${RESET}将${RED}启动${RESET}安卓版${YELLOW}XSDL${RESET}，并于9秒后自动启动${BOLD}${DEBIAN_FOLDER}${RESET}的${BLUE}x11${RESET}。
				You can also type ${GREEN}startxsdl${RESET} to ${YELLOW}start ${BLUE}xclient & server${RESET}.
				-------------------
				您也可以在${BOLD}${DEBIAN_FOLDER}${RESET}容器内输${GREEN}startvnc${RESET}来单独启动${BLUE}tight或tigervnc服务${RESET}，输${RED}stopvnc${RESET}停止
				-------------------
				You can type ${GREEN}startvnc${RESET} to start ${BLUE}tight/tigervnc server${RESET},type ${RED}stopvnc${RESET} to stop it.
				-------------------
		${BOLD}小提示06${RESET}:
				在${BOLD}${DEBIAN_FOLDER}${RESET}容器内输${GREEN}tmoe t${RESET}启动软件安装及远程桌面配置${BLUE}管理工具${RESET}。
				You can type ${GREEN}tmoe t${RESET} to start ${BLUE}tmoe tools.${RESET}
				-------------------
		${BOLD}小提示07${RESET}:
				在宿主机的终端里输${GREEN}debian${RESET}单独启动${BLUE}${BOLD}${DEBIAN_FOLDER}${RESET}容器${RESET}，此时将不会自动启动远程桌面服务。
				You can type ${GREEN}debian${RESET} to start ${BLUE}${BOLD}${DEBIAN_FOLDER}${RESET} container.${RESET}
				在v1.10beta及其之后的版本中，${GREEN}debian${RESET}命令实际上调用了${GREEN}tmoe${RESET} ヽ(✿ﾟ▽ﾟ)ノ
				例如启动${BLUE}${CONTAINER_TYPE}${RESET} ${PURPLE}${DEBIAN_FOLDER}${RESET}容器的完整命令为${BOLD}${GREEN}tmoe ${CONTAINER_TYPE} ${LONG_DISTRO_NAME} ${LONG_DISTRO_CODE} ${LONG_DISTRO_ARCH}${RESET}
				如需了解简化版启动命令，则请您查看README。
				Although you can use the full command, we recommend that you use the simplified command.
				For example, chroot can be simplified to c, ubuntu can be simplified to u, and arch can be simplified to a.
				${YELLOW}o( =•ω•= )m${RESET}
				${BOLD}少女祈禱中...${RESET}
				-------------------
	EOF
}
tmoe_tips_2_en() {
    cat <<-EOF
		${BOLD}少女祈禱中...${RESET}
		${YELLOW}o( =•ω•= )m${RESET}
				You can type ${GREEN}startx11vnc${RESET} to ${YELLOW}start ${BLUE}x11vnc server.${RESET}
				------------------
				You can also type ${GREEN}startxsdl${RESET} to ${YELLOW}start ${BLUE}xclient & server${RESET}.
				-------------------
				Type ${GREEN}startvnc${RESET} to start ${BLUE}tight/tigervnc server${RESET},type ${RED}stopvnc${RESET} to stop it.
				-------------------
				Type ${GREEN}tmoe t${RESET} to start ${BLUE}tmoe tools.${RESET}
				-------------------
				The ${GREEN}debian${RESET} command actually calls ${GREEN}tmoe${RESET}
				If you want to start ${BLUE}${CONTAINER_TYPE}${RESET} ${PURPLE}${DEBIAN_FOLDER}${RESET}, the ${PURPLE}FULL COMMAND${BOLD} is ${GREEN}tmoe ${CONTAINER_TYPE} ${LONG_DISTRO_NAME} ${LONG_DISTRO_CODE} ${LONG_DISTRO_ARCH}${RESET}
				If you want to know the ${GREEN}simplified command${RESET}, please read the ${YELLOW}README${RESET}.
				Although you can use the full command, we recommend that you use the simplified command.
				For example, chroot can be simplified to c, ubuntu can be simplified to u, and arch can be simplified to a.
				-------------------
	EOF
}
case ${TMOE_LANG} in
zh_*UTF-8) tmoe_tips_2_zh ;;
*) tmoe_tips_2_en ;;
esac
################
uncompress_other_format_file() {
    if [ "${TMOE_CHROOT}" = "true" ]; then
        ${TMOE_CHROOT_PREFIX} ${GNU_TAR_BIN} -pxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
    elif [ "${LINUX_DISTRO}" = "Android" ]; then
        pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | proot --link2symlink ${GNU_TAR_BIN} -px
    else
        if [ $(command -v pv) ]; then
            pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | ${GNU_TAR_BIN} -px
        else
            ${GNU_TAR_BIN} -pxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
        fi
    fi

    if [[ ! -e "${DEBIAN_CHROOT}/usr/bin/env" && ! -e "${DEBIAN_CHROOT}/bin/busybox" ]]; then
        if [ "${LINUX_DISTRO}" = "Android" ]; then
            pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | proot --link2symlink ${GNU_TAR_BIN} -px
        else
            ${GNU_TAR_BIN} -pxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
        fi
        ${TMOE_CHROOT_PREFIX} chown -Rv 0:0 ${DEBIAN_CHROOT}
    fi
}
##############
uncompress_tar_lz4_file() {
    if [ "${TMOE_CHROOT}" = "true" ]; then
        ${TMOE_CHROOT_PREFIX} ${GNU_TAR_BIN} -I lz4 -pxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
    elif [ "${LINUX_DISTRO}" = "Android" ]; then
        pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | proot --link2symlink ${GNU_TAR_BIN} -I lz4 -px
    else
        if [ $(command -v pv) ]; then
            pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | ${GNU_TAR_BIN} -I lz4 -px
        else
            ${GNU_TAR_BIN} -I lz4 -pxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
        fi
    fi

    if [[ ! -e "${DEBIAN_CHROOT}/usr/bin/env" && ! -e "${DEBIAN_CHROOT}/bin/busybox" ]]; then
        if [ "${LINUX_DISTRO}" = "Android" ]; then
            pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | proot --link2symlink ${GNU_TAR_BIN} -I lz4 -px
        else
            ${GNU_TAR_BIN} -I lz4 -pxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
        fi
        ${TMOE_CHROOT_PREFIX} chown -Rv 0:0 ${DEBIAN_CHROOT}
    fi
    # TRUE_TMOE_ROOTFS_TAR_XZ=${TMOE_ROOTFS_TAR_XZ}
    # TMOE_ROOTFS_TAR=$(printf '%s\n' "${TMOE_ROOTFS_TAR_XZ}" | sed 's@.tar.lz4@.tar@')
    # cd ${CURRENT_TMOE_DIR}
    # rm -fv ${TMOE_ROOTFS_TAR} 2>/dev/null
    # lz4 -d ${TMOE_ROOTFS_TAR_XZ}
    # cd ${DEBIAN_CHROOT}

    # TMOE_ROOTFS_TAR_XZ=${TMOE_ROOTFS_TAR}
    # uncompress_other_format_file
    # TMOE_ROOTFS_TAR_XZ=${TRUE_TMOE_ROOTFS_TAR_XZ}
    # rm -fv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR}
}
###########
uncompress_tar_gz_file() {
    if [ "${TMOE_CHROOT}" = "true" ]; then
        ${TMOE_CHROOT_PREFIX} ${GNU_TAR_BIN} -pzxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
    elif [ "${LINUX_DISTRO}" = "Android" ]; then
        pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | proot --link2symlink ${GNU_TAR_BIN} -pzx
    else
        if [ $(command -v pv) ]; then
            pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | ${GNU_TAR_BIN} -pzx
        else
            ${GNU_TAR_BIN} -pzxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
        fi
    fi

    if [[ ! -e "${DEBIAN_CHROOT}/usr/bin/env" && ! -e "${DEBIAN_CHROOT}/bin/busybox" ]]; then
        if [ "${LINUX_DISTRO}" = "Android" ]; then
            pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | proot --link2symlink ${GNU_TAR_BIN} -pzx
        else
            ${GNU_TAR_BIN} -pzxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
        fi
        ${TMOE_CHROOT_PREFIX} chown -Rv 0:0 ${DEBIAN_CHROOT}
    fi
}
#####################
check_tar_xz_pv() {
    if [ $(command -v pv) ]; then
        pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | ${GNU_TAR_BIN} -pJx
    else
        ${GNU_TAR_BIN} -pJxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
    fi
}
#############
uncompress_tar_xz_file() {
    case ${TMOE_LANG} in
    zh_*UTF-8) printf "%s\n" "正在${GREEN}解压${BLUE}${TMOE_ROOTFS_TAR_XZ}...${RESET}" ;;
    esac
    printf "%s\n" "${GREEN}Extracting ${BLUE}${TMOE_ROOTFS_TAR_XZ}${RESET}, please ${YELLOW}wait${RESET}."
    if [ "${TMOE_CHROOT}" = "true" ]; then
        ${TMOE_CHROOT_PREFIX} ${GNU_TAR_BIN} -pJxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
    elif [ "${LINUX_DISTRO}" = "Android" ]; then
        pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | proot --link2symlink ${GNU_TAR_BIN} -pJx
    else
        check_tar_xz_pv
    fi

    if [[ ! -e "${DEBIAN_CHROOT}/usr/bin/env" && ! -e "${DEBIAN_CHROOT}/bin/busybox" ]]; then
        if [ "${LINUX_DISTRO}" = "Android" ]; then
            pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | proot --link2symlink ${GNU_TAR_BIN} -pJx
        else
            ${GNU_TAR_BIN} -Jpxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
        fi
        ${TMOE_CHROOT_PREFIX} chown -Rv 0:0 ${DEBIAN_CHROOT}
    fi
}
#############
uncompress_tar_zst_file() {
    if [ "${TMOE_CHROOT}" = "true" ]; then
        ${TMOE_CHROOT_PREFIX} ${GNU_TAR_BIN} -I zstd -pxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
    elif [ "${LINUX_DISTRO}" = "Android" ]; then
        pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | proot --link2symlink ${GNU_TAR_BIN} -I zstd -px
    else
        if [ $(command -v pv) ]; then
            pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | ${GNU_TAR_BIN} -I zstd -px
        else
            ${GNU_TAR_BIN} -I zstd -pxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
        fi
    fi

    if [[ ! -e "${DEBIAN_CHROOT}/usr/bin/env" && ! -e "${DEBIAN_CHROOT}/bin/busybox" ]]; then
        if [ "${LINUX_DISTRO}" = "Android" ]; then
            pv ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ} | proot --link2symlink ${GNU_TAR_BIN} -I zstd -px
        else
            ${GNU_TAR_BIN} -I zstd -pxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}
        fi
        ${TMOE_CHROOT_PREFIX} chown -Rv 0:0 ${DEBIAN_CHROOT}
    fi
}
#####################
#解压前已进入$DEBIAN_CHROOT目录
uncompress_tar_file() {
    case "${TMOE_ROOTFS_TAR_XZ:0-6:6}" in
    tar.xz) uncompress_tar_xz_file ;;
    tar.gz) uncompress_tar_gz_file ;;
    ar.zst | r.zstd) uncompress_tar_zst_file ;;
    ar.lz4)
        #此处不为tar.lz4
        uncompress_tar_lz4_file
        ;;
    *) uncompress_other_format_file ;;
    esac
    case ${TMOE_CHROOT} in
    true) ${TMOE_CHROOT_PREFIX} chown -v 0:0 ${DEBIAN_CHROOT} ;;
    esac
    ${TMOE_CHROOT_PREFIX} chmod 755 ${DEBIAN_CHROOT}
}
#######################
case ${DEBOOTSTRAP_DIR} in
${DEBIAN_CHROOT}) ;;
*) uncompress_tar_file ;;
esac
#################
REMOTEP10KFONT='8597c76c4d2978f4ba022dfcbd5727a1efd7b34a81d768362a83a63b798f70e5'
IOSEVKA_FONT='2b41066b8faea10f7f4356a280b011c2fa3cd007000e6eca25f2f9aaf8b44713'
IOSEVKA_FONT_02='740ffbf01a972697690611c099805690ed696bd4d6213b9e6311d7699cd29abf'
IOSEVKA_FONT_03='cb4f09f9ec1b0d21021dce6c6dbe4f7ecb4930cbea0c766da1fe478111a5844e'
INVONSOLATA_FONT='740ffbf01a972697690611c099805690ed696bd4d6213b9e6311d7699cd29abf'
MESLO_FONT='4ac3012945f484496c899dce3b6ff6ec1a7395a444e9bf5acdf004867334cd17'
MESLO_BOLD_FONT='43f8115a8432c29662cec5028cf39a1576cc312db115fe12f2b839d4345d42a9'
FIRA_CODE_FONT='752fc955417cbb4628336718591d2f2ab0836025717f08871cee2aa0a95a0a57'
LOCALFONT="$(sha256sum ~/.termux/font.ttf 2>/dev/null | cut -c 1-64)" || LOCALFONT="0"
mkdir -pv ${DEBIAN_CHROOT}/tmp
case ${LOCALFONT} in
${REMOTEP10KFONT} | ${IOSEVKA_FONT} | ${MESLO_FONT} | ${MESLO_BOLD_FONT} | ${IOSEVKA_FONT_02} | ${INVONSOLATA_FONT} | ${FIRA_CODE_FONT} | ${IOSEVKA_FONT_03}) cp -f ~/.termux/font.ttf ${DEBIAN_CHROOT}/tmp 2>/dev/null ;;
*)
    MESLO_FONT_DIR="${HOME}/.config/tmoe-zsh/fonts/fonts/Iosevka"
    if [ -e "${MESLO_FONT_DIR}" ]; then
        cd ${MESLO_FONT_DIR}
        ${TMOE_CHROOT_PREFIX} cp -f 'Iosevka Term Bold Italic Nerd Font Complete Mono Windows Compatible.ttf' ${DEBIAN_CHROOT}/tmp/font.ttf
    fi
    ;;
esac
TMOE_TMP_DIR="${DEBIAN_CHROOT}/usr/local/etc/tmoe-linux/tmp"
${TMOE_CHROOT_PREFIX} mkdir -pv ${TMOE_TMP_DIR}

if [[ -s "${CONFIG_FOLDER}/default-dns.conf" ]]; then
    cp ${CONFIG_FOLDER}/default-dns.conf ${DEBIAN_CHROOT}/tmp/resolv.conf
    ${TMOE_CHROOT_PREFIX} cp ${CONFIG_FOLDER}/default-dns.conf ${TMOE_TMP_DIR}/resolv.conf
fi
#proot --link2symlink ${GNU_TAR_BIN} -Jxvf ${CURRENT_TMOE_DIR}/${TMOE_ROOTFS_TAR_XZ}||:
cd "${CURRENT_TMOE_DIR}"
printf "${YELLOW}"
cat <<-'EndOFneko'
	                                        
	                            .:7E        
	            .iv7vrrrrr7uQBBBBBBB:       
	           v17::.........:SBBBUg        
	        vKLi.........:. .  vBQrQ        
	   sqMBBBr.......... :i. .  SQIX        
	   BBQBBr.:...:....:. 1:.....v. ..      
	    UBBB..:..:i.....i YK:: ..:   i:     
	     7Bg.... iv.....r.ijL7...i. .Lu     
	  IB: rb...i iui....rir :Si..:::ibr     
	  J7.  :r.is..vrL:..i7i  7U...Z7i..     
	  ...   7..I:.: 7v.ri.755P1. .S  ::     
	    :   r:.i5KEv:.:.  :.  ::..X..::     
	   7is. :v .sr::.         :: :2. ::     
	   2:.  .u: r.     ::::   r: ij: .r  :  
	   ..   .v1 .v.    .   .7Qr: Lqi .r. i  
	   :u   .iq: :PBEPjvviII5P7::5Du: .v    
	    .i  :iUr r:v::i:::::.:.:PPrD7: ii   
	    :v. iiSrr   :..   s i.  vPrvsr. r.  
	     ...:7sv:  ..PL  .Q.:.   IY717i .7. 
	      i7LUJv.   . .     .:   YI7bIr :ur 
	     Y rLXJL7.:jvi:i:::rvU:.7PP XQ. 7r7 
	    ir iJgL:uRB5UPjriirqKJ2PQMP :Yi17.v 
	         :   r. ..      .. .:i  ...     
EndOFneko
printf "${RESET}"
####################
cat_tmoe_chroot_script() {
    source "${TMOE_SHARE_DIR}"/container/chroot/startup
}
cat_tmoe_nspawn_script() {
    source "${TMOE_SHARE_DIR}"/container/nspawn/startup
}
##############
get_android_host_name() {
    ANDROID_HOST_NAME=$(getprop ro.product.model | sed \
        -e 's@ @-@g' \
        -e 's@ @@g' \
        -e 's/[^0-9a-zA-Z.-]\+//g' \
        -e 's/^ \+\| \+$//g')
}
create_chroot_startup_script() {
    case ${LINUX_DISTRO} in
    Android)
        ANDROID_EMULATED_DIR='/storage/emulated'
        if [ ! -e "${DEBIAN_CHROOT}${ANDROID_EMULATED_DIR}" ]; then
            ${TMOE_CHROOT_PREFIX} mkdir -pv "${DEBIAN_CHROOT}${ANDROID_EMULATED_DIR}"

            ${TMOE_CHROOT_PREFIX} ln -s ../../media/sd "${DEBIAN_CHROOT}${ANDROID_EMULATED_DIR}/0"
        fi
        ;;
    esac
    cd "${CONFIG_FOLDER}"
    if [ -e "/system/bin/wm" ]; then
        TMOE_CHROOT_ETC="${DEBIAN_CHROOT}/usr/local/etc/tmoe-linux"
        ${TMOE_CHROOT_PREFIX} mkdir -pv "${TMOE_CHROOT_ETC}"
        WM_SIZE=$(su -c "/system/bin/wm size" | awk '{print $3}' | head -n 1)
        printf "%s\n" "${WM_SIZE}" >wm_size.txt
        chmod -v 666 wm_size.txt
        ${TMOE_CHROOT_PREFIX} mv wm_size.txt "${TMOE_CHROOT_ETC}"
    fi
    if [[ $(command -v getprop) && $(command -v am) ]]; then
        get_android_host_name
        printf "%s\n" "${ANDROID_HOST_NAME}" >hostname
        case $(hostname) in
        localhost | "") ${TMOE_CHROOT_PREFIX} hostname "${ANDROID_HOST_NAME}" 2>/dev/null ;;
        esac
    else
        [[ ! $(command -v hostname) ]] || printf "%s\n" "$(hostname)" >hostname
    fi
    if [[ -s hostname ]]; then
        ${TMOE_CHROOT_PREFIX} cp hostname "${DEBIAN_CHROOT}"/tmp
        ${TMOE_CHROOT_PREFIX} mv hostname "${DEBIAN_CHROOT}"/etc
    fi
    printf "%s\n" "Creating chroot startup script"
    printf "%s\n" "正在创建chroot容器启动脚本"
    #mkdir -pv /sdcard
    ${TMOE_CHROOT_PREFIX} mkdir -pv "${DEBIAN_CHROOT}"/media/sd
    ${TMOE_CHROOT_PREFIX} ln -sf ../media/sd "${DEBIAN_CHROOT}"/root/
    [[ -e ${DEBIAN_CHROOT}/sd ]] || ${TMOE_CHROOT_PREFIX} ln -sf media/sd "${DEBIAN_CHROOT}"/sd
    #fi
    if [ -d "/data/data/com.termux/files/home" ]; then
        ${TMOE_CHROOT_PREFIX} mkdir -pv ${DEBIAN_CHROOT}/media/termux
        ${TMOE_CHROOT_PREFIX} ln -sf ../media/termux ${DEBIAN_CHROOT}/root/
        if [ -h "${HOME}/storage/external-1" ]; then
            ${TMOE_CHROOT_PREFIX} mkdir -pv ${DEBIAN_CHROOT}/media/tf
            ${TMOE_CHROOT_PREFIX} ln -sf ../media/tf ${DEBIAN_CHROOT}/root/
            [[ -e ${DEBIAN_CHROOT}/tf ]] || ${TMOE_CHROOT_PREFIX} ln -sf media/tf ${DEBIAN_CHROOT}/tf
        fi
    fi
    if [[ -e ${DEBIAN_CHROOT}/etc/environment ]]; then
        cp ${DEBIAN_CHROOT}/etc/environment ${TMPDIR} 2>/dev/null || sudo cp ${DEBIAN_CHROOT}/etc/environment ${TMPDIR}
        sudo chmod 666 -v ${TMPDIR}/environment
    fi
    printf '%s\n' 'export TMOE_CHROOT=true' >>${TMPDIR}/environment
    sudo chmod a+r ${TMPDIR}/environment
    sudo mv ${TMPDIR}/environment ${DEBIAN_CHROOT}/etc/
    ##################
    #此处若不创建，将有可能导致chromium无法启动。
    ${TMOE_CHROOT_PREFIX} mkdir -pv ${DEBIAN_CHROOT}/run/shm ${DEBIAN_CHROOT}/etc/gitstatus ${TMOE_STARTUP_DIR}
    #${TMOE_CHROOT_PREFIX} ln -sf ../../etc/gitstatus ${DEBIAN_CHROOT}/root/.cache
    #chmod 1777 ${DEBIAN_CHROOT}/dev/shm 2>/dev/null
    cat_tmoe_chroot_script
    if [[ $(command -v getprop) && $(command -v am) ]]; then
        ANDROID_VERSION=$(getprop ro.build.version.release 2>/dev/null | cut -d '.' -f 1)
        case ${ANDROID_VERSION} in
        5 | 6 | 7) sudo sed -i -E 's@^(OLD_ANDROID_VERSION_COMPATIBILITY_MODE=).*@\1true@' ${TMOE_STARTUP_SCRIPT} ;;
        "") ;;
        *) sudo sed -i -E "s@^(UNSHARE_ENABLED=).*@\1true@" "${TMOE_STARTUP_SCRIPT}" ;;
        esac
        printf "%s\n" "ANDROID_VERSION=${ANDROID_VERSION}" >${TMPDIR}/.ANDROID_VERSION.txt
        sudo mv -vf ${TMPDIR}/.ANDROID_VERSION.txt ${DEBIAN_CHROOT}/tmp/
    else
        sudo sed -E -e "s@^(MOUNT_BIN=).*@\1default@g" \
            -i "${TMOE_STARTUP_SCRIPT}"
    fi
    if [[ ${SYSTEMD_NSPAWN} = true ]]; then
        cat_tmoe_nspawn_script
    fi

    case "$DISTRO_NAME" in
    dotnet*) ln_local_dotnet_to_share ;;
    esac
}
###################
create_tmoe_proot_stat_file() {
    cat >${TMOE_PROC_PREFIX}.${FILE_02} <<-'ENDOFSTAT'
		cpu  13543674 2263150 11590764 15571271 210309 1343827 851885 0 0 0
		cpu0 3629787 489276 3129188 15571051 210302 802654 516635 0 0 0
		cpu1 3221514 563397 2565534 19 0 168835 110203 0 0 0
		cpu2 2884314 491225 2361364 18 1 161981 92821 0 0 0
		cpu3 2664267 457057 2282166 21 0 166631 88732 0 0 0
		cpu4 365877 83980 417984 25 6 15600 10165 0 0 0
		cpu5 296831 71203 325638 39 0 9363 14383 0 0 0
		cpu6 262541 59844 288038 49 0 10350 10848 0 0 0
		cpu7 218543 47168 220852 49 0 8413 8098 0 0 0
		intr 1168051864 0 0 0 276005458 0 24952856 5 4 5 0 0 958 302 0 0 0 543988 116 0 1 0 92 184 0 0 0 0 0 0 0 2 0 145446 16538 11 11 358496 0 1779 0 0 0 0 0 1761 106944 0 221398 21826498 15065436 42829013 0 361294 4515 66197491 0 0 82 0 0 0 95 11438 0 0 0 0 0 0 0 0 0 0 288050 6 5498890 688446 388694 0 0 0 0 0 1674782 2042455 0 0 0 0 0 90 120387 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 7 190 0 1434 3096 2536 13 13822 11167 0 0 485674 0 4 3244478 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9327 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 18 0 0 0 0 30003 0 0 0 1471954 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3975713 62570 292 1841582 5903677 88 1324421 35786 38 0 95 601 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 77575 30048 0 680 0 106 0 0 0 0 0 0 0 38 0 0 0 0 0 0 116 111 112 0 113 80 17256 201 0 0 0 0 0 0 0 0 1071 0 12984 5 151277 20 171 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6969 0 45 0 0 4309 20 0 10 4 0 0 0 0 618 0 0 587152 46371 1206 0 493 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
		ctxt 1941467212
		btime 1597149124
		processes 1324243
		procs_running 9
		procs_blocked 1
		softirq 268005113 132391 49905524 287215 24847758 108137456 132391 1472849 45583820 0 37505709
	ENDOFSTAT
}
###############
check_tmoe_proot_container_proc() {
    if [ ! -e "${TMOE_PROC_PATH}" ]; then
        mkdir -pv "${TMOE_PROC_PATH}"
    fi
    #######
    FILE_02=stat
    TMOE_PROC_FILE=$(sed -n p /proc/${FILE_02} 2>/dev/null)
    if [ -z "${TMOE_PROC_FILE}" ]; then
        create_tmoe_proot_stat_file
        sed -i "s@##test02#@@" "${TMOE_STARTUP_SCRIPT}"
    fi
    #######
    FILE_03='/proc/bus/pci/devices'
    TMOE_PROC_FILE=$(sed -n p ${FILE_03} 2>/dev/null)
    [[ -n "${TMOE_PROC_FILE}" ]] || sed -i "s@##test04#@@" "${TMOE_STARTUP_SCRIPT}"
    ######
    #不要读取kmsg
    for i in buddyinfo cgroups consoles crypto devices diskstats execdomains fb filesystems interrupts iomem ioports kallsyms keys key-users kpageflags loadavg locks misc modules pagetypeinfo partitions sched_debug softirqs timer_list uptime vmallocinfo vmstat zoneinfo; do
        TMOE_PROC_FILE=$(sed -n p /proc/${i} 2>/dev/null)
        if [ -z "${TMOE_PROC_FILE}" ]; then
            printf "%s\n" "检测到您无权读取${BLUE}/proc/${i}${RESET},修复中..."
            printf "%s\n" "${GREEN}Fixing${RESET} ${YELLOW}/proc/${i}${RESET}..."
            sed -i "s@##${i}#@@" "${TMOE_STARTUP_SCRIPT}"
        fi
    done
    unset i
    #######
    FILE_01=version
    TMOE_PROC_FILE=$(sed -n p /proc/${FILE_01} 2>/dev/null)
    if [ -z "${TMOE_PROC_FILE}" ]; then
        printf "%s\n" "检测到您无权读取${BLUE}/proc/${FILE_01}${RESET},正在自动伪造新文件..."
        printf "%s\n" "你的version文件内容将被伪造成${YELLOW}$(uname -a) (gcc version 10.1.0 20200630 (prerelease) (GCC) )${RESET}"
        printf "%s\n" "$(uname -a) (gcc version 10.1.0 20200630 (prerelease) (GCC) )" >"${TMOE_PROC_PREFIX}.${FILE_01}"
        sed -i "s@##test01#@@" "${TMOE_STARTUP_SCRIPT}"
    fi
}
###########
set_proot_container_env() {
    touch "${DEBIAN_CHROOT}"/etc/environment
    printf "%s\n" \
        "export TMOE_PROOT=true" \
        "export MOZ_FAKE_NO_SANDBOX=1" \
        >>"${DEBIAN_CHROOT}"/etc/environment
}
create_dotnet_symlink() {
    # double DEBIAN_CHROOT
    DOUBLE_PATH="${DEBIAN_CHROOT}/${DEBIAN_CHROOT}/usr/local"
    mkdir -pv "${DOUBLE_PATH}/dotnet"
    rm -rfv "${DOUBLE_PATH}/dotnet"
    ln -svf /usr/local/dotnet "${DOUBLE_PATH}"
}
enable_dotnet_comp_mode() {
    case ${TRUE_ARCH_TYPE} in
    arm64)
        case ${ARCH_TYPE} in
        arm64)
            sed -E \
                -e "s@^(DOT_NET_6_COMPATIBLE_MODE=).*@\1true@g" \
                -e "s@^(PROOT_BIN=).*@\1\"compatibility\"@g" \
                -e "s@^(SHARE_PROOT_LOADER=).*@\1true@g" \
                -i "${TMOE_STARTUP_SCRIPT}"
            ;;
        esac
        ;;
    esac
}
ln_local_dotnet_to_share() {
    mkdir -p "${DEBIAN_CHROOT}"/usr/share
    ln -svf /usr/local/dotnet "${DEBIAN_CHROOT}"/usr/share
}
create_proot_startup_script() {
    printf "%s\n" "Creating proot startup script"
    printf "%s\n" "正在创建proot容器启动脚本 ${TMOE_STARTUP_SCRIPT}"
    TMOE_PROC_PATH="${DEBIAN_CHROOT}/usr/local/etc/tmoe-linux/proot_proc"
    TMOE_PROC_PREFIX="${TMOE_PROC_PATH}/.tmoe-container"
    mkdir -pv "${TMOE_STARTUP_DIR}"
    source ${TMOE_SHARE_DIR}/container/proot/startup
    if [ -e "${DEBIAN_CHROOT}/etc/environment" ]; then
        if ! grep -Eq '^[^#]*export.*MOZ_FAKE_NO_SANDBOX=' ${DEBIAN_CHROOT}/etc/environment; then
            set_proot_container_env
        fi
    else
        set_proot_container_env
    fi
    case "$DISTRO_NAME" in
    dotnet*)
        create_dotnet_symlink
        ln_local_dotnet_to_share
        enable_dotnet_comp_mode
        ;;
    esac
    cd ${CONFIG_FOLDER}
    if [[ $(command -v getprop) && $(command -v am) ]]; then
        get_android_host_name
        printf "%s\n" "${ANDROID_HOST_NAME}" >hostname
        ANDROID_VERSION=$(getprop ro.build.version.release 2>/dev/null | cut -d '.' -f 1)
        case ${ANDROID_VERSION} in
        5 | 6) sed -i -E 's@^(OLD_ANDROID_VERSION_COMPATIBILITY_MODE=).*@\1true@' ${TMOE_STARTUP_SCRIPT} ;;
        esac
        printf "%s\n" \
            '#!/usr/bin/env sh' \
            'PATH=$PATH:/system/bin exec /system/bin/getprop "$@"' \
            >${TMPDIR}/getprop
        chmod -v a+rx ${TMPDIR}/getprop
        mv -vf ${TMPDIR}/getprop "${DEBIAN_CHROOT}"/tmp/
    else
        [[ ! $(command -v hostname) ]] || printf "%s\n" "$(hostname)" >hostname
    fi
    case ${CONTAINER_DISTRO} in
    arch | archlinux | manjaro | solus)
        sed -E -e "s@^(PROOT_H=).*@\1true@g" \
            -i "${TMOE_STARTUP_SCRIPT}"
        ;;
    esac

    case ${TRUE_ARCH_TYPE} in
    arm64 | amd64)
        case ${ARCH_TYPE} in
        armhf | i386 | mipsel)
            sed -E -e "s@^(QEMU_32_ENABLED=).*@\1true@g" \
                -e "s@^(PROOT_BIN=).*@\1\"32\"@g" \
                -e "s@^(MOUNT_SYSTEM=).*@\1false@g" \
                -e "s@^(MOUNT_APEX=).*@\1false@g" \
                -i "${TMOE_STARTUP_SCRIPT}"
            ;;
        esac
        ;;
    esac
    case ${TRUE_ARCH_TYPE} in
    arm64 | armhf) [[ ${ARCH_TYPE} != i386 ]] || sed -E -e "s@^(MOUNT_TERMUX=).*@\1false@g" -i "${TMOE_STARTUP_SCRIPT}" ;;
    esac
    ############
    case ${TRUE_ARCH_TYPE} in
    "${ARCH_TYPE}") ;;
    *)
        sed -E -e "s@^(MOUNT_SYSTEM=).*@\1false@g" \
            -e "s@^(MOUNT_APEX=).*@\1false@g" \
            -i "${TMOE_STARTUP_SCRIPT}"
        if grep -q '^QEMU_USER_STATIC=.*false' "${TMOE_STARTUP_SCRIPT}"; then
            sed -E -e "s@^(MOUNT_SYSTEM=).*@\1true@g" \
                -e "s@^(MOUNT_APEX=).*@\1true@g" \
                -i "${TMOE_STARTUP_SCRIPT}"
        fi
        ;;
    esac
    [[ -z ${QEMU_ARCH} ]] || sed -i -E "s@^(QEMU_ARCH=).*@\1\"${QEMU_ARCH}\"@" "${TMOE_STARTUP_SCRIPT}"

    if [[ -s hostname ]]; then
        ${TMOE_CHROOT_PREFIX} cp hostname "${DEBIAN_CHROOT}"/tmp
        ${TMOE_CHROOT_PREFIX} mv hostname "${DEBIAN_CHROOT}"/etc
    fi
}
#########
if [ ! -e "${CONFIG_FOLDER}/gitstatus" ]; then
    mkdir -pv "${CONFIG_FOLDER}"/gitstatus
else
    ${TMOE_CHROOT_PREFIX} chmod 777 -Rv "${CONFIG_FOLDER}"/gitstatus
fi
if [ -e "${DEBIAN_CHROOT}"/etc/os-release ]; then
    if grep -q 'Ubuntu' "${DEBIAN_CHROOT}"/etc/os-release 2>/dev/null; then
        ${TMOE_CHROOT_PREFIX} touch "${DEBIAN_CHROOT}"/root/.hushlogin
        ${TMOE_CHROOT_PREFIX} touch "${DEBIAN_CHROOT}"/home/ubuntu/.hushlogin 2>/dev/null
    fi
fi
case ${TMOE_CHROOT} in
true) create_chroot_startup_script ;;
*)
    create_proot_startup_script
    check_tmoe_proot_container_proc
    ;;
esac
${TMOE_CHROOT_PREFIX} chmod -R a+rx "${TMOE_STARTUP_DIR}"
#######################################################
cat >${PREFIX}/bin/startvnc <<-ENDOFVNC
	#!/usr/bin/env bash
	vnc_warning() {
		printf "%s \033[33m%s\033[m %s \033[32m%s\033[m %s\n" "Starting" "vncserver" ",if you can not start it, then type" "tmoe t" ",and reinstall desktop."
		${PREFIX}/bin/tmoe pr vnc
	}
	if [ -e "${CONFIG_FOLDER}/chroot_container" ]; then
		${PREFIX}/bin/tmoe ch vnc
	elif [ -d "${DEBIAN_CHROOT}/root/.vnc" ]; then
		${PREFIX}/bin/tmoe pr vnc
	else
		vnc_warning
	fi
ENDOFVNC
#ln -sf ${PREFIX}/bin/startvnc ${PREFIX}/bin/startx11vnc
cat >${PREFIX}/bin/startx11vnc <<-ENDOFX11VNC
	#!/usr/bin/env bash
	vnc_warning() {
		printf "%s \033[33m%s\033[m %s \033[32m%s\033[m %s\n" "Starting" "x11vnc server" ",if you can not start it, then type" "tmoe t" ",and reinstall desktop."
		${PREFIX}/bin/tmoe pr x11
	}
	if [ -e "${CONFIG_FOLDER}/chroot_container" ]; then
		${PREFIX}/bin/tmoe ch x11
	elif [ -d "${DEBIAN_CHROOT}/root/.vnc" ];then
		${PREFIX}/bin/tmoe pr x11
	else
		vnc_warning
	fi
ENDOFX11VNC
#ln -s ${PREFIX}/bin/startx11vnc ${HOME}/vnc 2>/dev/null
###############
cat >${PREFIX}/bin/novnc <<-ENDOFNOVNC
	#!/usr/bin/env bash
	vnc_warning() {
		printf "%s \033[33m%s\033[m %s \033[32m%s\033[m %s\n" "Starting" "novnc" ",if you can not start it, then type" "tmoe t" ",and reinstall desktop."  
		${PREFIX}/bin/tmoe pr novnc
	}
	if [ -e "${CONFIG_FOLDER}/chroot_container" ]; then
		${PREFIX}/bin/tmoe ch novnc
	elif [ -d "${DEBIAN_CHROOT}/root/.vnc" ];then
		${PREFIX}/bin/tmoe pr novnc
	else
		vnc_warning
	fi
ENDOFNOVNC
###############
#此處僅適配Android,故shebang爲termux目錄
cat >${PREFIX}/bin/stopvnc <<-'ENDOFSTOPVNC'
	#!/data/data/com.termux/files/usr/bin/env bash
	[[ ! $(command -v termux-wake-unlock) ]] || termux-wake-unlock 2>/dev/null
	pulseaudio --kill 2>/dev/null
	sh -c "$(ps -e | grep -Ev "sshd|pkill|systemd" | awk '{print $4}' | sed '/(/d' | sed 's/^/pkill &/g')"
ENDOFSTOPVNC
#################
#不要单引号
cat >${PREFIX}/bin/startxsdl <<-ENDOFXSDL
	#!/usr/bin/env bash
	vnc_warning() {
		printf "%s \033[33m%s\033[m %s \033[32m%s\033[m %s\n" "Starting" "X" ",if you can not start it, then type" "tmoe t" ",and reinstall desktop."
		${PREFIX}/bin/tmoe pr xs
	}
	if [ -e "${CONFIG_FOLDER}/chroot_container" ]; then
		${PREFIX}/bin/tmoe ch xs
	elif [ -d "${DEBIAN_CHROOT}/root/.vnc" ];then
		${PREFIX}/bin/tmoe pr xs
	else
		vnc_warning
	fi
ENDOFXSDL
################
#aria2c --console-log-level=warn --no-conf --allow-overwrite=true -d ${PREFIX}/bin -o debian-i 'https://gitee.com/mo2/linux/raw/master/share/old-version/share/app/manager'
#############
printf '%s\n' 'Giving startup script execution permission'
printf "%s\n" "正在赋予启动脚本执行权限"
cd ${PREFIX}/bin
ln -sf "${TMOE_SHARE_DIR}"/app/tmoe ./
ln -svf tmoe tome
if [ ! $(command -v debian-i) ]; then
    ln -sf "${TMOE_SHARE_DIR}"/app/manager ./debian-i
fi
for i in debian startvnc stopvnc debian-i startxsdl startx11vnc tmoe novnc; do
    chmod -v a+rx ${i}
    [[ ! $(command -v termux-fix-shebang) ]] || termux-fix-shebang ${i}
done
################
printf "%s\n" "You can type rm ${ROOTFS_DIR}/${TMOE_ROOTFS_TAR_XZ} to delete the image file"
printf "%s\n" "您可以输${RED}rm ${ROOTFS_DIR}/${TMOE_ROOTFS_TAR_XZ}${RESET}来删除容器镜像文件"
ls -lh "${ROOTFS_DIR}/${TMOE_ROOTFS_TAR_XZ}"
########################
if [ ! -d "${DEBIAN_CHROOT}/usr/local/bin" ]; then
    ${TMOE_CHROOT_PREFIX} mkdir -pv "${DEBIAN_CHROOT}"/usr/local/bin
fi
#cd ${DEBIAN_CHROOT}/usr/local/bin
cd "${CONFIG_FOLDER}"
CURRENT_MONTH=$(date -u +%Y%m)
case ${CURRENT_MONTH} in
2021* | 202201)
    if [[ -e neofetch ]]; then
        if [[ $(sha256sum neofetch | awk '{print $1}') = bd3564aa793309792687c241808f31907c0294652c50a7459b54dd0359383c20 ]]; then
            rm -fv neofetch
        fi
    fi
    [[ -e "neofetch" ]] || curl -Lo "neofetch" 'https://gitee.com/mirrors/neofetch/raw/2b559cb8c62088dcbe997f6bb5a27002a9c22e27/neofetch'
    ;;
*) [[ -e "neofetch" ]] || curl -Lo "neofetch" 'https://gitee.com/mirrors/neofetch/raw/master/neofetch' ;;
esac

if [[ -e "debian-i" ]]; then
    chmod 666 debian-i
    rm -f debian-i
fi
#curl -Lo "debian-i" 'https://gitee.com/mo2/linux/raw/master/share/old-version/tools/app/tool'
cp -f "${TMOE_GIT_DIR}"/share/old-version/tools/app/tool ./debian-i
chmod a+rx neofetch debian-i

${TMOE_CHROOT_PREFIX} cp neofetch debian-i "${DEBIAN_CHROOT}"/usr/local/bin

${TMOE_CHROOT_PREFIX} chmod u+w -v "${DEBIAN_CHROOT}/root"
if [ ! -s "zsh-i.sh" ]; then
    curl -Lo zsh-i.sh 'https://gitee.com/mo2/zsh/raw/2/2'
fi
#sed -i 's:#!/usr/bin/env bash:#!/usr/bin/env bash:' zsh-i.sh
cp -f "${TMOE_SHARE_DIR}"/container/profile/configure_zsh ./zsh.sh
chmod a+rx zsh.sh zsh-i.sh
${TMOE_CHROOT_PREFIX} cp zsh-i.sh zsh.sh "${DEBIAN_CHROOT}"/root
${TMOE_CHROOT_PREFIX} cp -r "${TMOE_SHARE_DIR}"/container/profile "${DEBIAN_CHROOT}"/tmp
${TMOE_CHROOT_PREFIX} cp -r "${TMOE_SHARE_DIR}"/container/profile "${TMOE_TMP_DIR}"
${TMOE_CHROOT_PREFIX} chmod -R 1777 "${DEBIAN_CHROOT}"/tmp/profile "${TMOE_TMP_DIR}"
#chmod u+x ./*
###########
MANJARO_LINUX=false
[[ ${MANJARO_LINUX} = false ]] || ${TMOE_CHROOT_PREFIX} sed -i 's@^#SigLevel.*@SigLevel = Never@' "${DEBIAN_CHROOT}/etc/pacman.conf"
########
if [ -f "${TMOE_LOCALE_FILE}" ]; then
    TMOE_LOCALE_NEW_PATH="${DEBIAN_CHROOT}/usr/local/etc/tmoe-linux"
    ${TMOE_CHROOT_PREFIX} mkdir -pv "${TMOE_LOCALE_NEW_PATH}"
    ${TMOE_CHROOT_PREFIX} cp -f "${TMOE_LOCALE_FILE}" "${TMOE_LOCALE_NEW_PATH}"
    ${TMOE_CHROOT_PREFIX} chmod a+rw "${TMOE_LOCALE_NEW_PATH}"/locale.txt
fi
case ${TMOE_LANG} in
zh_*UTF-8) LNK_MENU_FILE="${HOME}/容器选择菜单.sh" ;;
ja_*UTF-8) LNK_MENU_FILE="${HOME}/天萌-コンテナ-メニュー.sh" ;;
*) LNK_MENU_FILE="${HOME}/TMOE-CONTAINER-MENU.sh" ;;
esac
ln -sf "${TMOE_SHARE_DIR}"/container/debian/lnk-menu "${LNK_MENU_FILE}"
[[ ! $(command -v termux-fix-shebang) ]] || termux-fix-shebang "${LNK_MENU_FILE}"
########################
#cd ${DEBIAN_CHROOT}/root
#无权限进入chroot容器的root目录
case ${TMOE_CHROOT} in
true)
    cd "${CONFIG_FOLDER}"
    ;;
*)
    cd "${DEBIAN_CHROOT}"/root
    ############
    [[ ! -e .bash_profile ]] || mv -f .bash_profile .bash_profile.bak 2>/dev/null
    [[ ! -e .bash_login ]] || mv -f .bash_login .bash_login.bak 2>/dev/null
    if [ ! -f ".profile" ]; then
        printf "\n" >>.profile
    else
        mv -f .profile .profile.bak
    fi
    ;;
esac
##################
#case ${TMOE_CHROOT} in
#true)
#rm -f /var/run/dbus/pid 2>/dev/null
#dbus-daemon --system --fork 2>/dev/null;;
#esac
############
#curl -Lo '.profile' 'https://gitee.com/mo2/linux/raw/master/profile.sh'
#chmod u+x .profile
#不要将profile转换为外部脚本，否则将影响sed
cat >'.profile' <<-'ENDOFbashPROFILE'
	RED=$(printf '\033[31m')
	GREEN=$(printf '\033[32m')
	YELLOW=$(printf '\033[33m')
	BLUE=$(printf '\033[34m')
	PURPLE=$(printf '\033[35m')
	CYAN=$(printf '\033[36m')
	RESET=$(printf '\033[m')
	BOLD=$(printf '\033[1m')
	TMOE_TMP_DIR=/usr/local/etc/tmoe-linux/tmp
	if [ -s /usr/local/etc/tmoe-linux/container.txt ]; then
	    #.dockerenv
	    export WEEKLY_BUILD_CONTAINER=true
	fi
	TMOE_LOCALE_FILE=/usr/local/etc/tmoe-linux/locale.txt
	if [[ ! $(command -v pkg) ]]; then
	    for i in apt dnf zypper; do
	        if [[ $(command -v ${i}) ]]; then
	            ln -s $(command -v ${i}) /usr/bin/pkg
	            break
	        fi
	    done
	fi
	if [ -s /tmp/getprop ]; then
	    chmod -v a+rx /tmp/getprop
	    mkdir -pv /usr/local/bin
	    mv -fv /tmp/getprop /usr/local/bin
	fi
	if [ $(command -v chpasswd) ]; then
	    printf "%s\n" "root:root" | chpasswd
	fi
	cd ${HOME}
	NEOFETCH_BIN_FILE="/usr/local/bin/neofetch"
	if [ -x /usr/bin/neofetch ]; then
	    rm -f ${NEOFETCH_BIN_FILE}
	    if [[ $(command -v lolcat) ]]; then
	        printf "%s\n" "${GREEN}neofetch | lolcat${RESET}"
	        /usr/bin/neofetch | lolcat
	    else
	        printf "%s\n" "${GREEN}neofetch${RESET}"
	        /usr/bin/neofetch
	    fi
	fi
	if [[ -e ${NEOFETCH_BIN_FILE} ]]; then
	    chmod a+rx ${NEOFETCH_BIN_FILE}
	    if [[ -e /usr/bin/bash || -e /bin/bash ]]; then
	        printf "%s\n" "${GREEN}neofetch${RESET}"
	        ${NEOFETCH_BIN_FILE}
	    fi
	fi
	###############
	unset TMOE_GITHUB
	###tmoe-github TMOE_GITHUB=true
	if ! grep -q "localhost" /etc/hosts 2>/dev/null; then
	    cat >>/etc/hosts <<-EOF
			127.0.0.1       localhost
			::1     localhost ip6-localhost ip6-loopback
			ff02::1 ip6-allnodes
			ff02::2 ip6-allrouters
		EOF
	fi
	if [[ -s "/tmp/hostname" ]]; then
	    NEW_HOST_NAME=$(head -n 1 /tmp/hostname)
	    cp -f /tmp/hostname /etc
	    #[[ ! $(command -v hostname) ]] || hostname ${NEW_HOST_NAME} 2>/dev/null
	    #sed -i "1s@LXC_NAME@${NEW_HOST_NAME}@" /etc/hosts 2>/dev/null
	    if ! grep -q "${NEW_HOST_NAME}" /etc/hosts 2>/dev/null; then
	        printf "%s\n" \
				"127.0.0.1 ${NEW_HOST_NAME}" \
				"::1 ${NEW_HOST_NAME}" \
				>>/etc/hosts
	    fi
	fi
	if [[ $(command -v hostname) ]]; then
	    if ! grep -q "$(hostname)" /etc/hosts 2>/dev/null; then
	        printf "%s\n" \
				"127.0.0.1 $(hostname) $(hostname -f)" \
				"::1 $(hostname) $(hostname -f)" \
				>>/etc/hosts
	    fi
	fi
	[[ ! -e /etc/hostname ]] || cat /etc/hostname
	[[ ! -e /etc/hosts ]] || cat /etc/hosts
	if [[ "${TMOE_CHROOT}" = 'true' && $(command -v groupadd) && -e /tmp/.ANDROID_VERSION.txt ]]; then
	    printf "%s\n" "Adding groups ..."
	    printf "%s\n" "This might take a while."
	    groupadd aid_system -g 1000 || groupadd aid_system -g 1074
	    groupadd aid_radio -g 1001
	    groupadd aid_bluetooth -g 1002
	    groupadd aid_graphics -g 1003
	    groupadd aid_input -g 1004
	    groupadd aid_audio -g 1005
	    groupadd aid_camera -g 1006
	    groupadd aid_log -g 1007
	    groupadd aid_compass -g 1008
	    groupadd aid_mount -g 1009
	    groupadd aid_wifi -g 1010
	    groupadd aid_adb -g 1011
	    groupadd aid_install -g 1012
	    groupadd aid_media -g 1013
	    groupadd aid_dhcp -g 1014
	    groupadd aid_sdcard_rw -g 1015
	    groupadd aid_vpn -g 1016
	    groupadd aid_keystore -g 1017
	    groupadd aid_usb -g 1018
	    groupadd aid_drm -g 1019
	    groupadd aid_mdnsr -g 1020
	    groupadd aid_gps -g 1021
	    groupadd aid_media_rw -g 1023
	    groupadd aid_mtp -g 1024
	    groupadd aid_drmrpc -g 1026
	    groupadd aid_nfc -g 1027
	    groupadd aid_sdcard_r -g 1028
	    groupadd aid_clat -g 1029
	    groupadd aid_loop_radio -g 1030
	    groupadd aid_media_drm -g 1031
	    groupadd aid_package_info -g 1032
	    groupadd aid_sdcard_pics -g 1033
	    groupadd aid_sdcard_av -g 1034
	    groupadd aid_sdcard_all -g 1035
	    groupadd aid_logd -g 1036
	    groupadd aid_shared_relro -g 1037
	    groupadd aid_dbus -g 1038
	    groupadd aid_tlsdate -g 1039
	    groupadd aid_media_ex -g 1040
	    groupadd aid_audioserver -g 1041
	    groupadd aid_metrics_coll -g 1042
	    groupadd aid_metricsd -g 1043
	    groupadd aid_webserv -g 1044
	    groupadd aid_debuggerd -g 1045
	    groupadd aid_media_codec -g 1046
	    groupadd aid_cameraserver -g 1047
	    groupadd aid_firewall -g 1048
	    groupadd aid_trunks -g 1049
	    groupadd aid_nvram -g 1050
	    groupadd aid_dns -g 1051
	    groupadd aid_dns_tether -g 1052
	    groupadd aid_webview_zygote -g 1053
	    groupadd aid_vehicle_network -g 1054
	    groupadd aid_media_audio -g 1055
	    groupadd aid_media_video -g 1056
	    groupadd aid_media_image -g 1057
	    groupadd aid_tombstoned -g 1058
	    groupadd aid_media_obb -g 1059
	    groupadd aid_ese -g 1060
	    groupadd aid_ota_update -g 1061
	    groupadd aid_automotive_evs -g 1062
	    groupadd aid_lowpan -g 1063
	    groupadd aid_hsm -g 1064
	    groupadd aid_reserved_disk -g 1065
	    groupadd aid_statsd -g 1066
	    groupadd aid_incidentd -g 1067
	    groupadd aid_secure_element -g 1068
	    groupadd aid_lmkd -g 1069
	    groupadd aid_llkd -g 1070
	    groupadd aid_iorapd -g 1071
	    groupadd aid_gpu_service -g 1072
	    groupadd aid_network_stack -g 1073
	    groupadd aid_shell -g 2000
	    groupadd aid_cache -g 2001
	    groupadd aid_diag -g 2002
	    groupadd aid_oem_reserved_start -g 2900
	    groupadd aid_oem_reserved_end -g 2999
	    groupadd aid_net_bt_admin -g 3001
	    groupadd aid_net_bt -g 3002
	    groupadd aid_inet -g 3003
	    groupadd aid_net_raw -g 3004
	    groupadd aid_net_admin -g 3005
	    groupadd aid_net_bw_stats -g 3006
	    groupadd aid_net_bw_acct -g 3007
	    groupadd aid_readproc -g 3009
	    groupadd aid_wakelock -g 3010
	    groupadd aid_uhid -g 3011
	    groupadd aid_everybody -g 9997
	    groupadd aid_misc -g 9998
	    groupadd aid_nobody -g 9999
	    groupadd aid_app_start -g 10000
	    groupadd aid_app_end -g 19999
	    groupadd aid_cache_gid_start -g 20000
	    groupadd aid_cache_gid_end -g 29999
	    groupadd aid_ext_gid_start -g 30000
	    groupadd aid_ext_gid_end -g 39999
	    groupadd aid_ext_cache_gid_start -g 40000
	    groupadd aid_ext_cache_gid_end -g 49999
	    groupadd aid_shared_gid_start -g 50000
	    groupadd aid_shared_gid_end -g 59999
	    #groupadd aid_overflowuid -g 65534 2>/dev/null || groupadd aid_overflowuid -g 65535
	    #添加65534 group将导致opensuse的system-user-nobody配置失败。
	    groupadd aid_isolated_start -g 99000
	    groupadd aid_isolated_end -g 99999
	    groupadd aid_user_offset -g 100000
	    #usermod -a -G aid_bt,aid_bt_net,aid_inet,aid_net_raw,aid_admin root
	    usermod -a -G aid_system,aid_radio,aid_bluetooth,aid_graphics,aid_input,aid_audio,aid_camera,aid_log,aid_compass,aid_mount,aid_wifi,aid_adb,aid_install,aid_media,aid_dhcp,aid_sdcard_rw,aid_vpn,aid_keystore,aid_usb,aid_drm,aid_mdnsr,aid_gps,aid_media_rw,aid_mtp,aid_drmrpc,aid_nfc,aid_sdcard_r,aid_clat,aid_loop_radio,aid_media_drm,aid_package_info,aid_sdcard_pics,aid_sdcard_av,aid_sdcard_all,aid_logd,aid_shared_relro,aid_dbus,aid_tlsdate,aid_media_ex,aid_audioserver,aid_metrics_coll,aid_metricsd,aid_webserv,aid_debuggerd,aid_media_codec,aid_cameraserver,aid_firewall,aid_trunks,aid_nvram,aid_dns,aid_dns_tether,aid_webview_zygote,aid_vehicle_network,aid_media_audio,aid_media_video,aid_media_image,aid_tombstoned,aid_media_obb,aid_ese,aid_ota_update,aid_automotive_evs,aid_lowpan,aid_hsm,aid_reserved_disk,aid_statsd,aid_incidentd,aid_secure_element,aid_lmkd,aid_llkd,aid_iorapd,aid_gpu_service,aid_network_stack,aid_shell,aid_cache,aid_diag,aid_oem_reserved_start,aid_oem_reserved_end,aid_net_bt_admin,aid_net_bt,aid_inet,aid_net_raw,aid_net_admin,aid_net_bw_stats,aid_net_bw_acct,aid_readproc,aid_wakelock,aid_uhid,aid_everybody,aid_misc,aid_nobody,aid_app_start,aid_app_end,aid_cache_gid_start,aid_cache_gid_end,aid_ext_gid_start,aid_ext_gid_end,aid_ext_cache_gid_start,aid_ext_cache_gid_end,aid_shared_gid_start,aid_shared_gid_end,aid_isolated_start,aid_isolated_end,aid_user_offset root
	    usermod -g aid_inet _apt 2>/dev/null
	    usermod -a -G aid_inet,aid_net_raw portage 2>/dev/null
	    printf "%s" "" #空行
	fi
	debian_sources_list() {
	    sed -i 's/^deb/##&/g' /etc/apt/sources.list
	    #stable-backports会出错，需改为buster-backports
	    cat >>/etc/apt/sources.list <<-'EndOfFile'
					#deb http://mirrors.bfsu.edu.cn/debian/ stable main contrib non-free
					#deb http://mirrors.bfsu.edu.cn/debian/ stable-updates main contrib non-free
					#deb http://mirrors.bfsu.edu.cn/debian/ buster-backports main contrib non-free
					#deb http://mirrors.bfsu.edu.cn/debian-security/ stable/updates main contrib non-free
					deb http://mirrors.bfsu.edu.cn/debian/ sid main contrib non-free
				EndOfFile
	    #请注意：若服务器添加了debian sid之外的自动构建任务，需要在此处修改软件源。
	    if [[ ${WEEKLY_BUILD_CONTAINER} = true ]]; then
	        if grep -q 'unstable main' /etc/apt/sources.list; then
	            sed -i "s@unstable@sid@g" /etc/apt/sources.list
	        elif ! grep -Eq 'sid|Sid' /etc/issue; then
	            sed -i "s@unstable@sid@g" /etc/apt/sources.list
	            SOURCELISTCODE=$(grep VERSION_CODENAME /etc/os-release | cut -d '=' -f 2 | head -n 1)
	            VERSION_ID=$(grep VERSION_ID /etc/os-release | awk -F '=' '{print $2}' | head -n 1 | cut -d '"' -f 2)
	            BACKPORTCODE=$(grep PRETTY_NAME /etc/os-release | head -n 1 | cut -d '=' -f 2 | cut -d '"' -f 2 | awk -F ' ' '$0=$NF' | cut -d '/' -f 1 | cut -d '(' -f 2 | cut -d ')' -f 1)
	            if ((VERSION_ID >= 11)); then
	                sed -i "s@stable/updates@${SOURCELISTCODE}-security@g" /etc/apt/sources.list
	            fi
	            sed -E -e "s@#(deb.*mirrors.)@\1@g" \
	                -e 's@^.*debian/ sid@#&@g' \
	                -e "s@buster(-backports)@${BACKPORTCODE}\1@g" \
	                -e "s@stable@${SOURCELISTCODE}@g" \
	                -i /etc/apt/sources.list
	        fi
	    fi
	}
	##############################
	kali_sources_list() {
	    #printf "%s\n" "检测到您使用的是Kali系统"
	    sed -i 's/^deb/##&/g' /etc/apt/sources.list
	    cat >>/etc/apt/sources.list <<-"EndOfSourcesList"
					#​Kali has various different branches to choose from (please take the time to read which one would be the best option for your setup), and you may be able to switch or include additional repositories.​kali-rolling (Default & frequently updated)​.
					#deb http://http.kali.org/kali kali-rolling main non-free contrib
					#​kali-last-snapshot (Point release so more “stable” & the “safest”)​
					#deb http://http.kali.org/kali kali-last-snapshot main non-free contrib
					#deb http://mirrors.huaweicloud.com/kali/ kali-last-snapshot main contrib non-free
					#kali-experimental (Packages which are under testing - often used with the rolling repository)​
					#deb http://http.kali.org/kali kali-experimental main non-free contrib
					#deb http://mirrors.bfsu.edu.cn/kali/ kali-rolling main non-free contrib
					deb http://mirrors.ustc.edu.cn/kali/ kali-rolling main non-free contrib
					#deb http://mirrors.huaweicloud.com/debian/ stable main contrib non-free
				EndOfSourcesList
	    #注意：kali-rolling添加debian testing源后，可能会破坏系统依赖关系，可以添加stable源（暂未发现严重影响）
	}
	######################
	ubuntu_sources_list() {
	    #默认为ports源，armbian无需使用sed进行替换。
	    sed -i 's/^deb/##&/g' /etc/apt/sources.list
	    cat >>/etc/apt/sources.list <<-'EndOfFile'
					# deb http://mirrors.huaweicloud.com/ubuntu-ports/ focal-proposed main restricted universe multiverse
					deb http://mirrors.bfsu.edu.cn/ubuntu-ports/ focal main restricted universe multiverse
					deb http://mirrors.bfsu.edu.cn/ubuntu-ports/ focal-updates main restricted universe multiverse
					deb http://mirrors.bfsu.edu.cn/ubuntu-ports/ focal-backports main restricted universe multiverse
					deb http://mirrors.bfsu.edu.cn/ubuntu-ports/ focal-security main restricted universe multiverse
				EndOfFile
	    touch ~/.hushlogin
	    touch /home/ubuntu/.hushlogin 2>/dev/null
	    if grep -q 'Bionic Beaver' "/etc/os-release"; then
	        sed -i 's/focal/bionic/g' /etc/apt/sources.list
	    fi
	    case $(uname -m) in
	    i*86 | x86_64 | amd64) sed -i 's@ubuntu-ports/@ubuntu/@g' /etc/apt/sources.list ;;
	    esac
		VERSION_CODENAME=$(grep 'VERSION_CODENAME' /etc/os-release | awk -F'=' '{print $2}')
	    [[ -z ${VERSION_CODENAME} ]] || sed -i "s@focal@${VERSION_CODENAME}@g" /etc/apt/sources.list

	}
	#########################
	modify_mint_source_list() {
	    sed -i 's@^@#&@g' ${SOURCE_LIST}.bak 2>/dev/null
	    sed -i "s@packages.linuxmint.com@${CHINA_MIRROR}/linuxmint@g" ${SOURCE_LIST} 2>/dev/null
	    sed -i "s@archive.ubuntu.com@${CHINA_MIRROR}@g" ${SOURCE_LIST} 2>/dev/null
	    sed -n p ${SOURCE_LIST}.bak >>${SOURCE_LIST} 2>/dev/null
	}
	mint_sources_list() {
	    printf "%s\n" "检测到您使用的是Linux Mint"
	    CHINA_MIRROR='mirrors.huaweicloud.com'
	    SOURCE_LIST=/etc/apt/sources.list
	    SOURCE_LIST_02="${SOURCE_LIST}.d/official-package-repositories.list"
	    SOURCE_LIST_03="${SOURCE_LIST}.d/official-source-repositories.list"
	    cp -fv ${SOURCE_LIST} ${SOURCE_LIST}.bak 2>/dev/null
	    if [[ ${TMOE_GITHUB} != true ]]; then
	        modify_mint_source_list
	    fi
	    cp -fv ${SOURCE_LIST_02} ${SOURCE_LIST_02}.bak
	    if [[ ${TMOE_GITHUB} != true ]]; then
	        if [[ -e ${SOURCE_LIST_02} ]]; then
	            SOURCE_LIST=${SOURCE_LIST_02}
	            modify_mint_source_list
	        fi
	    fi
	    if [[ -e ${SOURCE_LIST_03} ]]; then
	        mv -vf ${SOURCE_LIST_03} ${SOURCE_LIST_03}.bak
	    fi
	}
	####################
	if [[ ! -e /etc/apt/sources.list.d/raspi.list ]]; then
	    case $(uname -m) in
	    mips* | risc*) ;;
	    *)
	        if grep -q 'Debian' "/etc/issue"; then
	            debian_sources_list
	            case $(uname -m) in
	            arm* | mips*) sed -i 's@163.com@huaweicloud.com@g' /etc/apt/sources.list ;;
	            esac
	        fi
	        ;;
	    esac
	fi
	###############
	TUNA_MIRROR_URL='mirrors.bfsu.edu.cn'
	if [ -e /etc/apt/sources.list.d/armbian.list ]; then
	    case $(uname -m) in
	    aarch64) dpkg --remove-architecture armhf ;;
	    esac
	    cd /etc/apt/sources.list.d
	    cp armbian.list armbian.list.bak
	    sed -i 's/^/#&/g' armbian.list.bak
	    sed -i 's@apt.armbian.com@mirrors.bfsu.edu.cn/armbian@g' armbian.list
	    #sed -i '$ a\deb http://mirrors.bfsu.edu.cn/armbian/ bullseye main bullseye-utils bullseye-desktop' /etc/apt/sources.list.d/armbian.list
	    cat armbian.list.bak >>armbian.list
	    rm -f armbian.list.bak
	    cd ~
	elif [ -e /etc/apt/sources.list.d/raspi.list ]; then
	    cd /etc/apt/sources.list.d
	    cp raspi.list raspi.list.bak
	    sed -i 's/^/#&/g' raspi.list.bak
	    #http://archive.raspberrypi.org/debian/ buster main
	    #deb http://mirrors.bfsu.edu.cn/raspbian/raspbian/ buster main non-free contrib rpi
	    #mirrors.bfsu.edu.cn/raspberrypi/
	    sed -i "s@archive.raspberrypi.org/debian@${TUNA_MIRROR_URL}/raspberrypi@g" raspi.list
	    cat raspi.list.bak >>raspi.list
	    rm -f raspi.list.bak
	    cd ..
	    cp sources.list sources.list.bak
	    sed -i "s@raspbian.raspberrypi.org/raspbian@${TUNA_MIRROR_URL}/raspbian/raspbian@g" sources.list
	    sed -i 's/^/#&/g' sources.list.bak
	    cat sources.list.bak >>sources.list
	    cd ~
	fi
	###############
	if grep -q 'Kali' "/etc/issue"; then
	    kali_sources_list
	elif [ "$(cut -c 1-6 /etc/issue)" = "Ubuntu" ]; then
	    ubuntu_sources_list
	elif grep -q 'Mint' "/etc/issue"; then
	    mint_sources_list
	elif grep -Eq 'deepin|uos\.com' "/etc/os-release"; then
	    if grep -q '20' /etc/issue; then
	        DEBIAN_VERSION='buster'
	    elif grep -q '15\.5 SP2' /etc/issue; then
	        DEBIAN_VERSION='stretch'
	        sed -i 's@mirrors.bfsu.edu.cn@packages.deepin.com@g' /etc/apt/sources.list
	        apt update
	        apt install -y apt-transport-https 2>/dev/null
	    else
	        DEBIAN_VERSION='stable'
	    fi
	    DEBIAN_STABLE_LIST='/etc/apt/sources.list.d/debian-stable.list'
	    sed -i 's@http:@https:@g' /etc/apt/sources.list 2>/dev/null
	    printf "%s\n" "deb https://mirrors.bfsu.edu.cn/debian/ ${DEBIAN_VERSION} main" >${DEBIAN_STABLE_LIST}
	    chmod a+r -v ${DEBIAN_STABLE_LIST}
	elif grep -q 'OpenWrt' "/etc/os-release"; then
	    cp /etc/opkg/distfeeds.conf /etc/opkg/distfeeds.conf.bak
	    sed -i 's@downloads.openwrt.org@mirrors.bfsu.edu.cn/openwrt@g' /etc/opkg/distfeeds.conf
	fi
	#################
	unset TMOE_GITHUB
	###tmoe-github TMOE_GITHUB=true
	#勿删上面那条注释
	###tmoe-github sed -i 's/^deb/# &/g;s/^##deb/deb/g' /etc/apt/sources.list
	##dns
	[[ ! -e /etc/apt/sources.list ]] || grep -v proposed /etc/apt/sources.list
	rm -f /etc/resolv.conf
	cat >/etc/resolv.conf <<-'EndOfFile'
		nameserver 114.114.114.114
		nameserver 114.114.115.115
		nameserver 240c::6666
		nameserver 240c::6644
		EndOfFile
	if [[ -s /tmp/resolv.conf ]]; then
	    cp -f /tmp/resolv.conf /etc
	elif [[ -s ${TMOE_TMP_DIR}/resolv.conf ]]; then
	    chmod 644 ${TMOE_TMP_DIR}/resolv.conf
	    cp -fv ${TMOE_TMP_DIR}/resolv.conf /etc
	    cp -f ${TMOE_TMP_DIR}/resolv.conf /tmp
	fi
	chmod -v 644 /etc/resolv.conf
	cat /etc/resolv.conf
	printf "%s\n" ""
	######################
	###################
	arch_linux_mirror_list() {
	    sed -i 's/^Server/#&/g' /etc/pacman.d/mirrorlist
	    case $(uname -m) in
	    aarch64 | arm*)
	        cat >>/etc/pacman.d/mirrorlist <<-'EndOfArchMirrors'
						## Archlinux arm
						Server = https://mirrors.ustc.edu.cn/archlinuxarm/$arch/$repo     
						Server = https://mirror.archlinuxarm.org/$arch/$repo
						Server = https://mirrors.bfsu.edu.cn/archlinuxarm/$arch/$repo
						Server = https://mirrors.tuna.tsinghua.edu.cn/archlinuxarm/$arch/$repo
						Server = https://mirrors.163.com/archlinuxarm/$arch/$repo
					EndOfArchMirrors
	        ;;
	    *)
	        cat >>/etc/pacman.d/mirrorlist <<-'EndOfArchMirrors'
						## Archlinux mirror list
						Server = https://mirrors.ustc.edu.cn/archlinux/$repo/os/$arch
						Server = http://mirrors.kernel.org/archlinux/$repo/os/$arch
						Server = https://mirrors.bfsu.edu.cn/archlinux/$repo/os/$arch
						Server = https://mirrors.huaweicloud.com/archlinux/$repo/os/$arch
						Server = https://mirrors.163.com/archlinux/$repo/os/$arch
					EndOfArchMirrors
	        ;;
	    esac
	}
	#############################
	manjaro_mirror_list() {
	    if [ "$(uname -m)" = "aarch64" ]; then
	        [[ ! $(command -v sed) ]] || sed -i 's/^Server/#&/g' /etc/pacman.d/mirrorlist 2>/dev/null
	        cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak
	        cat >/etc/pacman.d/mirrorlist <<-'EndOfArchMirrors'
						## Archlinux arm
						#Server = https://mirror.archlinuxarm.org/$arch/$repo
						#Server = https://mirrors.bfsu.edu.cn/archlinuxarm/$arch/$repo
						#Server = https://mirrors.huaweicloud.com/manjaro/arm-stable/$repo/$arch
						## Manjaro linux arm
						## Country : Netherlands
						#Server = https://manjaro.mirrors.lavatech.top/arm-stable/$repo/$arch
						## Country : France
						#Server = http://kibo.remi.lu/arm-stable/$repo/$arch
						## Country : Germany
						#Server = https://mirror.alpix.eu/manjaro/arm-stable/$repo/$arch
						## Country : Poland
						#Server = https://mirror.tuchola-dc.pl/manjaro/arm-stable/$repo/$arch
						## Country : New_Zealand
						#Server = http://manjaro.mirrors.theom.nz/arm-stable/$repo/$arch
						## Country : China
						Server = https://mirrors.bfsu.edu.cn/manjaro/arm-stable/$repo/$arch
						Server = https://mirrors.tuna.tsinghua.edu.cn/manjaro/arm-stable/$repo/$arch
						Server = https://mirrors.ustc.edu.cn/manjaro/arm-stable/$repo/$arch
					EndOfArchMirrors
	    elif [[ "$(uname -m)" = "x86_64" ]]; then
	        cat >/etc/pacman.d/mirrorlist <<-'EndOfArchMirrors'
						#Server = https://manjaro.mirrors.lavatech.top/stable/$repo/$arch
						#Server = https://manjaro.grena.ge/stable/$repo/$arch
						#Server = https://mirror.oldsql.cc/manjaro/stable/$repo/$arch
						Server = https://mirrors.bfsu.edu.cn/manjaro/stable/$repo/$arch
						Server = https://mirrors.ustc.edu.cn/manjaro/stable/$repo/$arch
						Server = https://mirrors.tuna.tsinghua.edu.cn/manjaro/stable/$repo/$arch     
					EndOfArchMirrors
	    fi
	}
	#################
	install_fakeroot() {
	    for i in whiptail whereis diff ip curl; do
	        if [ ! $(command -v ${i}) ]; then
	            case ${i} in
	            whiptail) DEP=libnewt ;;
	            whereis) DEP=util-linux ;;
	            diff) DEP=diffutils ;;
	            ip) DEP=iproute ;;
	            *) DEP=${i} ;;
	            esac
	            printf "%s\n" "${GREEN}pacman ${YELLOW}-S ${PURPLE}--noconfirm ${BLUE}${DEP}${RESET}"
	            pacman -S --noconfirm ${DEP}
	        fi
	    done

	    # for i in arch4edu-keyring fakeroot-tcp; do
	    i=fakeroot-tcp
	    printf "%s\n" "${GREEN}pacman ${YELLOW}-Sy --noconfirm ${BLUE}${i}${RESET}"
	    pacman -Sy --noconfirm ${i}
	    # done
	    cd ${HOME}
	}
	############
	add_arch_for_edu_repo() {
	    if ! grep -q 'arch4edu' /etc/pacman.conf; then
	        cat >>/etc/pacman.conf <<-'Endofpacman'
						[arch4edu]
						Server = https://mirrors.bfsu.edu.cn/arch4edu/$arch
						Server = https://mirrors.tuna.tsinghua.edu.cn/arch4edu/$arch
						Server = https://mirror.autisten.club/arch4edu/$arch
						Server = https://arch4edu.keybase.pub/$arch
						Server = https://mirror.lesviallon.fr/arch4edu/$arch
						Server = https://mirrors.tencent.com/arch4edu/$arch
						SigLevel = Never
					Endofpacman
	    fi
	}
	add_archlinuxcn_repo() {
	    if ! grep -q 'archlinuxcn' /etc/pacman.conf; then
	        cat >>/etc/pacman.conf <<-'Endofpacman'
						[archlinuxcn]
						Server = https://mirrors.bfsu.edu.cn/archlinuxcn/$arch
						Server = https://mirrors.tuna.tsinghua.edu.cn/archlinuxcn/$arch
						Server = https://repo.archlinuxcn.org/$arch
						SigLevel = Never
					Endofpacman
	    fi
	    printf "%s\n" "${GREEN}pacman ${YELLOW}-Syyu ${PURPLE}--noconfirm${RESET}"
	    pacman -Syyu --noconfirm
	}
	create_paru_script(){
		cat>paru<<-'EOFparu'
	#!/usr/bin/env bash
	if [ -e /usr/bin/paru ];then
		/usr/bin/paru $@
	else
		/opt/bin/paru $@
	fi
	EOFparu
	cat>yay<<-'EOFyay'
	#!/usr/bin/env bash
	if [ -e /usr/bin/yay ];then
	/usr/bin/yay $@
	else
	paru $@
	fi
	EOFyay
	install -Dm755 paru /usr/local/bin
	install -Dm755 yay /usr/local/bin
	}
	arch_linux_paru() {
		# pacman-key --populate archlinuxcn
		# archlinux-keyring archlinuxcn-keyring
	    for i in arch4edu-keyring paru; do
	        printf "%s\n" "${GREEN}pacman ${YELLOW}-Sy ${PURPLE}--noconfirm --needed ${BLUE}${i}${RESET}"
	        pacman -Sy --noconfirm --needed ${i}
	    done
		if [[ ! $(command -v paru) ]]; then
			get_arch_paru
		fi
	}
	get_arch_paru() {
		case $(uname -m) in
		x86_64) pacman -Sy --noconfirm --needed paru ;;
		armv7* | armv8l) 
		printf "%s\n" \
			"You should install ${GREEN}paru ${BLUE}manually${RESET}" \
			"${GREEN}git ${YELOW}clone --depth=1 ${BLUE}https://aur.archlinux.org/paru.git${RESET}" \
			"cd paru" \
			"makepkg -Si"
		;;
	    aarch64 | armv8* | armv9*)
		cd /tmp
		curl -Lo paru.tar.zst l.tmoe.me/paru-arm64 || curl -Lvo paru.tar.zst l.tmoe.me/paru-arm64-github
		tar -xvf paru.tar.zst
		mkdir -p /opt/bin
		install -Dm755 paru /opt/bin
		create_paru_script
		printf "%s\n" \
		"You should run ${GREEN}paru -Sy ${BLUE}paru-bin${RESET} to upgrade it."
		;;
		esac
		cd ~
	}
	#################
	#################
	if [ "$(cut -c 1-4 /etc/issue)" = "Arch" ]; then
	    [[ ${TMOE_GITHUB} = true ]] || arch_linux_mirror_list
	    [[ ! -e /etc/pacman.d/mirrorlist ]] || cat /etc/pacman.d/mirrorlist
	    if [[ ${WEEKLY_BUILD_CONTAINER} != true ]]; then
	        printf "%s\n" "${GREEN}pacman-key ${YELLOW}--init${RESET}"
	        printf "%s\n" "${GREEN}pacman-key ${YELLOW}--populate${RESET}"
	        pacman-key --init
	        pacman-key --populate
	        if [ -e "/etc/mkinitcpio.d/linux-armv7.preset" ]; then
	            printf "%s\n" "${GREEN}pacman ${PURPLE}-Rsc ${YELLOW}--noconfirm ${BLUE}linux-armv7${RESET}"
	            pacman -Rsc --noconfirm linux-armv7
	        fi
	        printf "%s\n" "${GREEN}pacman ${YELLOW}-Syu --noconfirm --needed ${BLUE}base-devel${RESET}"
	        pacman -Syu --noconfirm --needed base-devel
	    fi
	elif [ "$(cut -c 1-7 /etc/issue)" = "Manjaro" ]; then
	    [[ ${TMOE_GITHUB} = true ]] || manjaro_mirror_list
	    [[ ! -e /etc/pacman.d/mirrorlist ]] || cat /etc/pacman.d/mirrorlist
	    if [[ ${WEEKLY_BUILD_CONTAINER} != true ]]; then
	        printf "%s\n" "${GREEN}pacman-key ${YELLOW}--init${RESET}"
	        printf "%s\n" "${GREEN}pacman-key ${YELLOW}--populate${RESET}"
	        pacman-key --init
	        pacman-key --populate
	        printf "%s\n" "${GREEN}pacman ${YELLOW}-Syu --noconfirm ${BLUE}base base-devel${RESET}"
	        pacman -Syu --noconfirm base base-devel
	    fi
	fi

	if [[ -e "/etc/pacman.conf" && $(command -v grep) ]]; then
		sed -i.bak -E "s@^#(Color)@\1@" /etc/pacman.conf
	    if [[ ${WEEKLY_BUILD_CONTAINER} != true ]]; then
	        add_arch_for_edu_repo
	        add_archlinuxcn_repo
	        arch_linux_paru
	        cat /etc/pacman.conf
	    else
	        if [[ ! -x /usr/bin/paru && ! -x /opt/bin/paru ]]; then
	            get_arch_paru
	        fi
	        if [[ ${TMOE_CHROOT} = true ]]; then
	            i=gawk
	            printf "%s\n" "${GREEN}pacman ${YELLOW}-Sy --noconfirm ${BLUE}${i}${RESET}"
	            pacman -Sy --noconfirm ${i}
	        fi
	    fi
	fi

	#######################
	case ${TMOE_PROOT} in
	true)
	    for i in sd tf; do
	        if [[ -e "/media/${i}" && ! -e "/${i}" ]]; then
	            ln -sv media/${i} /
	        fi
	    done
	    for i in sd tf termux; do
	        if [[ -e "/media/${i}" && ! -e "/root/${i}" ]]; then
	            ln -sv ../media/${i} /root/
	        fi
	    done
	    unset i
	    ;;
	esac
	choose_vnc_port_5902_or_5903() {
	    if (whiptail --title "VNC PORT" --yes-button "5902" --no-button "5903" --yesno "請選擇VNC端口✨\nPlease choose a vnc port" 0 50); then
	        X11VNC_PORT=5902
	        DISPLAY_PORT=2
	    else
	        X11VNC_PORT=5903
	        DISPLAY_PORT=3
	    fi
	    sed -i -E "s@(DISPLAY)=.*@\1=:${DISPLAY_PORT}@" "$(command -v startvnc)"
	}
	set_vnc_passwd() {
	    TARGET_VNC_PASSWD=$(whiptail --inputbox "請設定6至8位VNC訪問密碼\nPlease type the password, the length is between 6 and 8" 0 50 --title "VNC PASSWORD" 3>&1 1>&2 2>&3)
	    if [ "$?" != "0" ]; then
	        printf "%s\n" "请重新输入密码"
	        printf "%s\n" "Please type the password again."
	        printf "%s\n" "Press enter to return."
	        read
	        set_vnc_passwd
	    elif [ -z "${TARGET_VNC_PASSWD}" ]; then
	        printf "%s\n" "请输入有效的数值"
	        printf "%s\n" "Please type a valid value"
	        printf "%s\n" "Press enter to return."
	        read
	        set_vnc_passwd
	    else
	        mkdir -pv ${HOME}/.vnc
	        cd ${HOME}/.vnc
	        printf "%s\n" "${TARGET_VNC_PASSWD}" | vncpasswd -f >passwd
	        chmod 600 -v passwd
	        [[ ! -e /usr/bin/startvnc ]] || ln -sf /usr/bin/startvnc /usr/local/bin/startvnc
	        mkdir -pv /etc/X11/xinit
	        [[ -e /etc/X11/xinit/Xsession ]] || cp -vf /root/.vnc/xstartup /etc/X11/xinit/Xsession
	        [[ $(command -v startxsd) ]] || printf "%s\n%s\n%s\n" '#!/bin/sh' "export DISPLAY=127.0.0.1:0" "/etc/X11/xinit/Xsession" >/usr/local/bin/startxsdl
	        chmod a+rx /usr/local/bin/startxsdl
	    fi
	}
	exit_tmoe_configuration() {
	    cd ~
	    rm -f ~/.zlogin ~/.profile zsh.sh zsh-i.sh 2>/dev/null
	    [[ ! -e ~/.profile.bak ]] || mv -f ~/.profile.bak ~/.profile 2>/dev/null
	    for i in zsh bash sh su; do
	        if [[ $(command -v ${i}) ]]; then
	            exec ${i}
	            break
	        fi
	    done
	    exit 0
	}
	if grep -q 'puppy_linux' /etc/os-release; then
	    choose_vnc_port_5902_or_5903
	    set_vnc_passwd
	    printf "%s\n" "You can type ${GREEN}startvnc${RESET} to start ${BLUE}tightvnc server${RESET},type ${RED}stopvnc${RESET} to stop it."
	    printf "%s\n" "当前系统已经了预装窗口管理器和tightvnc服务端,您可以输${GREEN}startvnc${RESET}来启动vnc服务端。"
	elif grep -q 'Solus' /etc/os-release; then
	    if [[ $(command -v debian-i) ]]; then
	        cp $(command -v debian-i) /usr/local/bin/tmoe
	    fi
	    printf "%s\n" "${GREEN}eopkg ${BLUE}update-repo${RESET}"
	    eopkg update-repo
	    eopkg help
	    exit_tmoe_configuration
	fi

	if grep -Eq 'puppy_linux|clear-linux-os|EulerOS|amazon_linux|Oracle Linux|VMware Photon OS|SteamOS GNU' /etc/os-release 2>/dev/null; then
	    exit_tmoe_configuration
	fi
	##############
	if [ -e "${TMOE_LOCALE_FILE}" ]; then
	    TMOE_LANG=$(head -n 1 ${TMOE_LOCALE_FILE})
	else
	    TMOE_LANG="zh_CN.UTF-8"
	fi
	TMOE_LANG_HALF=$(printf '%s\n' "${TMOE_LANG}" | cut -d '.' -f 1)
	TMOE_LANG_QUATER=$(printf '%s\n' "${TMOE_LANG}" | cut -d '.' -f 1 | cut -d '_' -f 1)

	case ${TMOE_LANG} in
	zh_*UTF-8)
	    printf "%s\n" "您已成功安装Container,之后可以输${YELLOW}debian${RESET}来进入debian container."
	    printf "%s\n" "Congratulations on your successful installation of GNU/Linux container. After that, you can type debian to enter the container."
	    printf '%s\n' '正在执行优化步骤，请勿退出!'
	    printf '%s\n' 'Optimization steps are in progress. Do not exit!'
	    #配置时区
	    printf '%s\n' 'Asia/Shanghai' >/etc/timezone
	    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
	    ;;
	*)
	    printf "%s\n" "Congratulations on your successful installation of GNU/Linux container. After that, you can type debian to enter the container. "
	    printf '%s\n' 'Optimization steps are in progress. Do not exit!'
	    printf '%s\n' 'UTC' >/etc/timezone
	    ln -svf /usr/share/zoneinfo/UTC /etc/localtime
	    ;;
	esac

	for i in /etc/gitstatus/timezone.txt /root/.cache/gitstatus/timezone.txt; do
	    if [[ -e ${i} ]]; then
	        TIMEZONE=$(head -n 1 ${i})
	        ln -svf /usr/share/zoneinfo/${TIMEZONE} /etc/localtime
	        cp -f ${i} /etc/timezone
	        chmod 644 -v /etc/timezone
	        break
	    fi
	done
	########################
	configure_openwrt() {
	    mkdir -pv /var/lock/
	    touch /var/lock/opkg.lock
	    opkg update
	    opkg install libustream-openssl ca-bundle ca-certificates bash dialog whiptail
	    printf "%s\n" "export PATH=\${PATH}:/usr/local/sbin:/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/games:/usr/local/games" >>~/.zshenv
	    rm -f ~/.profile ~/.zlogin 2>/dev/null
	    mv -f ~/.profile.bak ~/.profile 2>/dev/null
	    exec bash zsh.sh
	    exit 0
	}
	alpine_linux_configure() {
	    if [ "$(sed -n 2p /etc/os-release | cut -d '=' -f 2)" = "alpine" ]; then
	        [[ ${TMOE_GITHUB} = true ]] || sed -i 's/dl-cdn.alpinelinux.org/mirrors.bfsu.edu.cn/g' /etc/apk/repositories
	        cat /etc/apk/repositories
	        printf "%s\n" "${GREEN}apk ${YELLOW}add ${BLUE}bash tzdata newt sudo shadow${RESET}"
	        printf "%s\n" "${GREEN}apk ${YELLOW}upgrade${RESET}"
	        apk update
	        apk upgrade
	        apk add bash tzdata newt sudo shadow
	    fi
	    rm -f ~/.profile ~/.zlogin 2>/dev/null
	    mv -f ~/.profile.bak ~/.profile 2>/dev/null
	    #printf "%s\n" "您已成功安装Container,之后可以输${YELLOW}debian${RESET}来进入debian container."
	    #neofetch
	    exec bash zsh.sh
	    exit 0
	}
	############################
	opensuse_mirrors() {
	    if [ "$(uname -m)" = 'aarch64' ]; then
	        zypper mr -da
	        zypper addrepo -fcg https://mirrors.bfsu.edu.cn/opensuse/ports/aarch64/tumbleweed/repo/oss bfsu-mirror-oss
	        zypper --gpg-auto-import-keys refresh
	    elif [ "$(uname -m)" != 'armv7l' ]; then
	        zypper mr -da
	        zypper addrepo -fcg https://mirrors.bfsu.edu.cn/opensuse/tumbleweed/repo/oss/ bfsu-mirror-oss
	        zypper addrepo -fcg https://mirrors.bfsu.edu.cn/opensuse/tumbleweed/repo/non-oss/ bfsu-mirror-non-oss
	        zypper addrepo -fcg https://mirrors.bfsu.edu.cn/packman/suse/openSUSE_Tumbleweed/ bfsu-mirror_Tumbleweed
	        zypper --gpg-auto-import-keys refresh
	        #zypper dup --no-allow-vendor-change -y
	    fi
	}
	opensuse_linux_repo() {
	    LINUX_DISTRO='suse'
	    [[ ${TMOE_GITHUB} = true ]] || opensuse_mirrors
	    zypper in -y wget curl
	    sed -i "s@RC_LANG=.*@RC_LANG=${TMOE_LANG}@" /etc/sysconfig/language
	    sed -i "s@RC_LC_ALL=.*@RC_LC_ALL=${TMOE_LANG}@" /etc/sysconfig/language
	    sed -i "s@INSTALLED_LANGUAGES=@INSTALLED_LANGUAGES=${TMOE_LANG_HALF}@" /etc/sysconfig/language
	    zypper in -y glibc-locale glibc-i18ndata
	    zypper in -y translation-update-${TMOE_LANG_HALF}
	}
	################################
	if grep -q 'openSUSE' "/etc/os-release"; then
	    opensuse_linux_repo
	    zypper in -y newt
	elif grep -q 'Alpine Linux' "/etc/issue" 2>/dev/null; then
	    alpine_linux_configure
	elif grep -q 'OpenWrt' "/etc/os-release"; then
	    configure_openwrt
	fi
	##############################
	if [[ $(command -v apt) ]]; then
	    if [[ ! $(command -v eatmydata) ]]; then
	        printf "%s\n" "${GREEN}apt ${YELLOW}install -y ${BLUE}eatmydata${RESET}"
	        apt update 2>/dev/null || apt update 2>/dev/null
	        apt install -y eatmydata || apt install -y -f eatmydata
	    else
	        printf "%s\n" "${GREEN}eatmydata apt ${BLUE}update${RESET}"
	        eatmydata apt update || apt update
	    fi
	    if [[ ${TMOE_CHROOT} = true ]]; then
	        printf "%s\n" "${GREEN}eatmydata apt ${YELLOW}reinstall -y ${BLUE}perl-base${RESET}"
	        eatmydata apt-get install --reinstall -y perl-base 2>/dev/null || apt-get install --reinstall -y perl-base 2>/dev/null
	    fi
	    if [ ! $(command -v locale-gen) ]; then
	        printf "%s\n" "${GREEN}eatmydata apt ${YELLOW}install -y ${BLUE}locales${RESET}"
	        eatmydata apt install -y locales 2>/dev/null || apt install -y locales 2>/dev/null
	    fi
	fi
	STARTUP_FILE=/usr/local/etc/tmoe-linux/container/tmoe-linux-container
	if [[ -s ${STARTUP_FILE} ]]; then
	    if grep -q "^HOST_ARCH" ${STARTUP_FILE}; then
	        HOST_ARCH=$(grep "^HOST_ARCH=" ${STARTUP_FILE} | awk -F '=' '{print $2}' | cut -d '"' -f 2)
	        CONTAINER_ARCH=$(grep "^CONTAINER_ARCH=" ${STARTUP_FILE} | awk -F '=' '{print $2}' | cut -d '"' -f 2)
	        case ${HOST_ARCH} in
	        arm64 | armhf)
	            if [[ ${CONTAINER_ARCH} = i386 ]]; then
	                # sed -E -e "s@^(EXA_ENABLED=).*@\1true@g" -i "${STARTUP_FILE}"
	                if [[ $(command -v apt) ]]; then
	                    printf "%s\n" "${GREEN}apt ${YELLOW}reinstall -y ${BLUE}perl-base${RESET}"
	                    apt-get install --reinstall -y perl-base 2>/dev/null
	                    for i in perlbug unzip pigz; do
	                        if [[ -L /usr/bin/${i} ]]; then
	                            case ${i} in
	                            perlbug) DEP="perl" ;;
	                            *) DEP=${i} ;;
	                            esac
	                            printf "%s\n" "${GREEN}apt ${YELLOW}reinstall -y ${BLUE}${DEP}${RESET}"
	                            apt-get install --reinstall -y ${DEP} 2>/dev/null
	                        fi
	                    done
	                    for i in 6 7 8 9 10; do
	                        if [[ -L "/usr/bin/python3.${i}m" ]]; then
	                            printf "%s\n" "${GREEN}apt ${YELLOW}reinstall -y ${BLUE}python3.${i}-minimal${RESET}"
	                            apt-get install --reinstall -y python3.${i}-minimal 2>/dev/null
	                            dpkg --configure -a
	                            break
	                        fi
	                    done
	                fi
	            fi
	            ;;
	        esac
	    fi
	fi

	locale_def_utf8() {
	# glibc-common, libc-bin
	if [[ -z $(command -v localedef) ]]; then
		return 0
	fi

	local lang=${TMOE_LANG_HALF}

	# locale -a
	if (! localedef --list-archive | grep -qi "$lang.*utf.*8"); then
		printf "%s\n" \
			"${GREEN}Generating ${BLUE}locales ${YELLOW}(this might take a while)${PURPLE}..." \
			"${BLUE}${lang}.UTF-8${RESET}"

		# -c(--force), -v(--verbose), -f(--charmap), -i(--inputfile)
		localedef \
			-c \
			-i "${lang}" \
			-f UTF-8 \
			"${lang}".UTF-8
	fi
	}

	if grep -q 'ubuntu' /etc/os-release; then
	    if [ ! -e /usr/lib/locale/zh_CN ]; then
	        printf "%s\n" "${GREEN}eatmydata apt ${YELLOW}install -y ${BLUE}locales-all${RESET}"
	        eatmydata apt install -y locales-all 2>/dev/null || apt install -y locales-all 2>/dev/null
	    fi
	    printf "%s\n" "${GREEN}eatmydata apt ${YELLOW}install -y ${BLUE}^language-pack-${TMOE_LANG_QUATER}${RESET}"
	    eatmydata apt install -y ^language-pack-${TMOE_LANG_QUATER} 2>/dev/null || apt install -y ^language-pack-${TMOE_LANG_QUATER} 2>/dev/null
	fi

	mkdir -pv /etc/default
	printf "%s\n" "Configuring ${TMOE_LANG_HALF} environment..."
	cat >/etc/default/locale <<-EOF
				LANG=${TMOE_LANG}
				LANGUAGE=${TMOE_LANG_HALF}:${TMOE_LANG_QUATER}
				LC_ALL=${TMOE_LANG}
			EOF

	if [[ -n "$(command -v dpkg-query)" ]];then
		if (! dpkg-query -s locales-all >/dev/null 2>&1);then
			locale_def_utf8 2>/dev/null
		fi
	else
		locale_def_utf8 2>/dev/null
	fi
	source /etc/default/locale 2>/dev/null
	###############
	if [[ -e /etc/apt/sources.list.d/system76-ubuntu-pop-focal.list ]]; then
	    apt-cache show pop-desktop
	    printf "%s\n" "If you are using a systemd-nspawn container, then you can type ${GREEN}apt${RESET} ${YELLOW}install ${BLUE}pop-desktop${RESET} to install Pop\!OS desktop."
	    exit_tmoe_configuration
	fi
	#################
	if grep -Eq "Arch|Manjaro" '/etc/os-release' 2>/dev/null || grep -Eq "Arch|Manjaro" '/etc/issue'; then
	    if [[ ${WEEKLY_BUILD_CONTAINER} != true ]]; then
	        printf "%s\n" "${GREEN}pacman ${PURPLE}-R ${YELLOW}--noconfirm ${BLUE}fakeroot${RESET}"
	        pacman -R --noconfirm fakeroot 2>/dev/null
	        install_fakeroot
	    fi
	fi
	printf "$YELLOW"
	cat <<-'EndOFneko'
				                                     
				       DL.                           
				       QBBBBBKv:rr77ri:.             
				       gBBQdY7::::..::i7vv.          
				       UBd. . .:.........rBBBQBBBB5  
				       Pu  :..r......i:....BBBQBBB:  
				       ri.i:.j:...:. i7... uBBZrd:   
				 :     7.:7.7U.:..r: Yr:.. iQ1:qU    
				.Qi   .7.ii.X7:...L.:qr:...iB7ZQ     
				 .27. :r.r:L7i::.7r:vri:...rr  .     
				  v   ::.Yrviri:7v7v: ::...i.   i    
				      r:ir: r.iiiir..:7r...r   :P.2Y 
				      v:vi::.      :  ::. .qI7U1U :1 
				Qr    7.7.         :.i::. :Di:. i .v:
				v7..  s.r7.   ...   .:7i: rDi...r .. 
				 vi: .7.iDBBr  .r   .:.7. rPr:..r    
				 i   :virZBgi  :vrYJ1vYY .ruY:..i    
				     YrivEv. 7BBRBqj21I7 .77J:.:.PQ  
				    .1r:q.   rB52SKrj.:i i5isi.:i :.r
				    YvrY7    r.  . ru :: PIrj7.:r..v 
				   rSviYI..iuU .:.:i:.7.KPPiSr.:vr   
				  .u:Y:JQMSsJUv...   .rDE1P71:.7X7   
				  5  Ivr:QJ7JYvi....ir1dq vYv.7L.Y   
				  S  7Z  Qvr:.iK55SqS1PX  Xq7u2 :7   
				         .            i   7          

			EndOFneko
	printf "$RESET"
	####################
	if [[ $(command -v apt) ]]; then
	    if [[ ! $(command -v apt-extracttemplates) ]]; then
	        printf "%s\n" "${GREEN}eatmydata apt ${YELLOW}install -y ${BLUE}apt-utils${RESET}"
	        eatmydata apt install -y apt-utils 2>/dev/null || apt install -y apt-utils 2>/dev/null
	    fi

	    for i in curl sudo; do
	        if [[ ! $(command -v ${i}) ]]; then
	            printf "%s\n" "${GREEN}eatmydata apt ${YELLOW}install -y ${BLUE}${i}${RESET}"
	            eatmydata apt install -y ${i} || apt install -y ${i}
	        fi
	    done
	    if [[ ! -e /usr/sbin/update-ca-certificates ]]; then
	        printf "%s\n" "${GREEN}eatmydata apt ${YELLOW}install -y ${BLUE}ca-certificates${RESET}"
	        eatmydata apt install -y ca-certificates 2>/dev/null || apt install -y ca-certificates 2>/dev/null
	    fi
	    if grep -Eq 'squeeze|wheezy|stretch|jessie|CODENAME=xenial' "/etc/os-release"; then
	        eatmydata apt install -y apt-transport-https 2>/dev/null || apt install -y apt-transport-https 2>/dev/null
	    fi
	fi

	if [[ ! -e /etc/apt/sources.list.d/raspi.list && -e /etc/apt/sources.list ]]; then
	    case $(uname -m) in
	    riscv*) ;;
	    *)
	        if grep -Eq '^deb.*(huawei|tuna|bfsu|163)' /etc/apt/sources.list; then
	            printf "%s\n" "Replacing http software source list with https ..."
	            case ${TMOE_LANG} in
	            zh_*UTF-8) printf "%s\n" "正在将${PURPLE}http源${RESET}替换为${GREEN}https${RESET} ..." ;;
	            esac
	            case $(dpkg --print-architecture) in
	            armhf)
	                case $(uname -m) in
	                aarch64 | armv8l) ;;
	                *) sed -i 's@http:@https:@g' /etc/apt/sources.list ;;
	                esac
	                ;;
	            *) sed -i 's@http:@https:@g' /etc/apt/sources.list ;;
	            esac
	        fi
	        ;;
	    esac
	    sed -i 's@https://security@http://security@g' /etc/apt/sources.list
	fi
	##########################
	gentoo_gnu_linux_make_conf() {
	    LINUX_DISTRO=gentoo
	    #bash /etc/profile
	    mkdir -pv '/usr/portage'
	    case ${TMOE_LANG} in
	    zh_*UTF-8)
	        grep -q 'zh_CN' /etc/locale.gen || printf "%s\n" \
				"zh_CN.UTF-8 UTF-8" \
				"en_US.UTF-8 UTF-8" \
				>>/etc/locale.gen
	        locale-gen
	        GENTOOLOCALE="$(eselect locale list | grep 'zh_CN' | head -n 1 | cut -d '[' -f 2 | cut -d ']' -f 1)"
	        eselect locale set "${GENTOOLOCALE}"
	        printf '%s\n' \
				'ACCEPT_LICENSE="*"' \
				'MAKEOPTS="-j8"' \
				'L10N="zh-CN en-US"' \
				'LINGUAS="zh_CN en_US"' \
				'PORTDIR="/usr/portage"' \
				'DISTDIR="${PORTDIR}/distfiles"' \
				'PKGDIR="${PORTDIR}/packages"' \
				'GENTOO_MIRRORS="https://mirrors.bfsu.edu.cn/gentoo"' \
				'EMERGE_DEFAULT_OPTS="--ask --verbose=y --keep-going --with-bdeps=y --load-average"' \
				'FEATURES="${FEATURES} -userpriv -usersandbox -sandbox"' \
				>>/etc/portage/make.conf
	        ;;
	    *)
	        grep -q 'en_US' /etc/locale.gen || printf "%s\n" "en_US.UTF-8 UTF-8" >>/etc/locale.gen
	        locale-gen
	        printf '%s\n' \
				'ACCEPT_LICENSE="*"' \
				'MAKEOPTS="-j8"' \
				'PORTDIR="/usr/portage"' \
				'DISTDIR="${PORTDIR}/distfiles"' \
				'PKGDIR="${PORTDIR}/packages"' \
				'EMERGE_DEFAULT_OPTS="--ask --verbose=y --keep-going --with-bdeps=y --load-average"' \
				'FEATURES="${FEATURES} -userpriv -usersandbox -sandbox"' \
				>>/etc/portage/make.conf
	        ;;
	    esac
	    cat /etc/portage/make.conf
	    source /etc/portage/make.conf 2>/dev/null
	    mkdir -pv /etc/portage/repos.conf/
	    cat >/etc/portage/repos.conf/gentoo.conf <<-'EndofgentooConf'
					[gentoo]
					location = /usr/portage
					sync-type = rsync
					#sync-uri = rsync://rsync.mirrors.ustc.edu.cn/gentoo-portage/
					sync-uri = rsync://mirrors.bfsu.edu.cn/gentoo-portage/
					auto-sync = yes
				EndofgentooConf
	    source /etc/portage/repos.conf/gentoo.conf 2>/dev/null
	    rm -fv .profile ~/.zlogin
	    mv -f .profile.bak .profile 2>/dev/null
	    if grep -q 'Funtoo' /etc/os-release; then
	        emerge --sync
	        emerge emerge-webrsync
	    fi
	    emerge-webrsync
	    emerge --config sys-libs/timezone-data 2>/dev/null
	    GENTOO_NON_SYSTEMD_PROFILE="$(eselect profile list | grep -Ev 'desktop|hardened|developer|systemd|selinux|multilib' | grep stable | tail -n 1 | cut -d '[' -f 2 | cut -d ']' -f 1)"
	    [[ -n ${GENTOO_NON_SYSTEMD_PROFILE} ]] || GENTOO_NON_SYSTEMD_PROFILE=1
	    eselect profile set "${GENTOO_NON_SYSTEMD_PROFILE}"
	    eselect profile list
	    etc-update --automode -3
	    etc-update
	    #dispatch-conf
	    emerge -uvDN --with-bdeps=y @world
	    if [[ ! $(command -v ar) ]]; then
	        emerge -avk sys-devel/binutils
	    fi
	    emerge eix 2>/dev/null
	    eix-update
	    [[ $(command -v whiptail) ]] || emerge -av dev-libs/newt
	    #rm -f vnc* zsh* .profile
	}
	#############################
	void_linux_repository() {
	    LINUX_DISTRO='void'
	    LOCALE_FILE="/etc/default/libc-locales"
	    sed -i "s/^#.*${TMOE_LANG} UTF-8/${TMOE_LANG} UTF-8/" ${LOCALE_FILE} 2>/dev/null
	    if ! grep -Eq "^[^#]*${TMOE_LANG_HALF}" "${LOCALE_FILE}" 2>/dev/null; then
	        #sed -i 's@^@#&@g;s@##@#@g' ${LOCALE_FILE} 2>/dev/null
	        printf "\n" >>${LOCALE_FILE}
	        sed -i "$ a${TMOE_LANG} UTF-8" ${LOCALE_FILE}
	    fi
	    cat >/etc/locale.conf <<-'EOF'
				LANG=${TMOE_LANG}
				LANGUAGE=${TMOE_LANG_HALF}:${TMOE_LANG_QUATER}
				LC_ALL=${TMOE_LANG}
			EOF
	    mkdir -pv /etc/xbps.d
	    cp /usr/share/xbps.d/*-repository-*.conf /etc/xbps.d/
	    sed -i 's@https://alpha.de.repo.voidlinux.org@https://mirrors.bfsu.edu.cn/voidlinux@g' /etc/xbps.d/*-repository-*.conf
	    xbps-install -S
	    xbps-install -uy xbps
	    xbps-install -y wget curl newt
	    neofetch
	    xbps-reconfigure -f glibc-locales
	}
	##########################
	if grep -Eq 'Funtoo|Gentoo' '/etc/os-release'; then
	    gentoo_gnu_linux_make_conf
	elif grep -qi 'Void' '/etc/issue'; then
	    void_linux_repository
	fi
	####################
	if [[ $(command -v apt) ]]; then
	    apt update 2>/dev/null
	    apt list --upgradable 2>/dev/null
	    if [[ ! $(command -v curl) ]]; then
	        apt install -y curl apt-utils
	    fi
	    printf "%s\n" "Upgrading all packages ..."
	    printf "%s\n" "${GREEN}eatmydata apt ${YELLOW}-y ${BLUE}dist-upgrade${RESET}"
	    if [[ ${WEEKLY_BUILD_CONTAINER} != true && ! -e /etc/apt/sources.list.d/system76-ubuntu-pop-focal.list ]]; then
	        eatmydata apt upgrade -y 2>/dev/null
	        dpkg --configure -a
	        eatmydata apt dist-upgrade -y 2>/dev/null || apt dist-upgrade -y 2>/dev/null
	        dpkg --configure -a
	    else
	        printf "%s\n" "You are using weekly/moothly build container,${PURPLE}skipping automatic upgrade${RESET}..."
	    fi
	    if [[ ! $(command -v pkill) ]]; then
	        printf "%s\n" "${GREEN}eatmydata apt ${YELLOW}install -y ${BLUE}procps${RESET}"
	        eatmydata apt install -y procps 2>/dev/null || apt install -y procps 2>/dev/null
	    fi
	    #i + dialog
	    for i in whiptail; do
	        if [[ ! $(command -v ${i}) ]]; then
	            printf "%s\n" "${GREEN}eatmydata apt ${YELLOW}install -y ${BLUE}${i}${RESET}"
	            eatmydata apt install -y ${i} 2>/dev/null || apt install -y ${i} 2>/dev/null
	        fi
	    done
	    apt clean 2>/dev/null
	fi
	#############################
	#grep -q 'export DISPLAY' /etc/profile || printf "%s\n" "export DISPLAY=":1"" >>/etc/profile
	printf "%s\n" "Welcome to Debian GNU/Linux."
	sed -n p /etc/issue 2>/dev/null || sed -n p /etc/os-release
	uname -a
	rm -f .profile ~/.zlogin 2>/dev/null
	if [ -f ".profile.bak" ]; then
	    mv -f .profile.bak .profile
	fi
	####################
	#fedora mirrors.bfsu.edu.cn/fedora/releases/
	#########################
	fedora_rpmfusion_repo() {
	    printf "%s\n" "You are using fedora system. Adding rpmfusion repo ..."
	    printf "%s\n" "${GREEN}dnf ${YELLOW}install -y --nogpgcheck ${BLUE}https://mirrors.bfsu.edu.cn/rpmfusion/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm https://mirrors.bfsu.edu.cn/rpmfusion/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm${RESET}"
	    dnf install -y --nogpgcheck https://mirrors.bfsu.edu.cn/rpmfusion/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm https://mirrors.bfsu.edu.cn/rpmfusion/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm
	    case ${TMOE_GITHUB} in
	    true) ;;
	    *)
	        for i in $(ls /etc/yum.repos.d/rpmfusion*repo | grep -v rawhide); do
	            #cp -vf ${i} ${i}.backup
	            sed -e 's!^metalink=!#metalink=!g' \
	                -e 's!^#baseurl=!baseurl=!g' \
	                -e 's!//download1\.rpmfusion\.org/!//mirrors.bfsu.edu.cn/rpmfusion/!g' \
	                -e 's!http://mirrors\.bfsu!https://mirrors.bfsu!g' \
	                -i ${i}
	        done
	        ;;
	    esac
	}
	######################
	if [ "$(grep 'ID=' /etc/os-release | head -n 1 | cut -d '=' -f 2 | cut -d '"' -f 2)" = "fedora" ]; then
	    tar -Ppzcf ~/yum.repos.d-backup.tar.gz /etc/yum.repos.d
	    mv -f ~/yum.repos.d-backup.tar.gz /etc/yum.repos.d
	    FEDORA_VERSION="$(grep 'VERSION_ID' /etc/os-release | cut -d '=' -f 2)"
	    sed -i -E "s@(enabled)=1@\1=0@" /etc/yum.repos.d/fedora-updates-testing-modular.repo /etc/yum.repos.d/fedora-updates-testing.repo
	    if grep -q '=rawhide' /etc/os-release; then
	        sed -i -E 's@^(gpgcheck)=.*@\1=0@g' /etc/yum.repos.d/*.repo
	    fi

	    if [[ ! -e /tmp/resolv.conf ]]; then
	        cp -f /etc/resolv.conf /tmp
	    fi
	    if ((${FEDORA_VERSION} >= 32)); then
	        if ! grep -q '=rawhide' /etc/os-release; then
	            [[ ${TMOE_CHROOT} != true ]] || fedora_rpmfusion_repo
	        fi
	    fi
	    printf "%s\n" "${GREEN}dnf ${YELLOW}update -y${RESET}"
	    if [[ ${WEEKLY_BUILD_CONTAINER} != true ]]; then
	        dnf update -y
	    else
	        printf "%s\n" "You are using weekly/moothly build container,${PURPLE}skipping automatic upgrade${RESET}..."
	    fi
	    [[ $(command -v hostname) ]] || dnf install -y hostname
	    [[ $(command -v systemctl) ]] || dnf install -y systemd
	    if [[ -s /tmp/resolv.conf ]]; then
	        rm -f /etc/resolv.conf
	        #更新系统后，dns解析文件会被systemd的配置所覆盖
	        cp -f /tmp/resolv.conf /etc
	    fi
	    [[ $(command -v ip) ]] || dnf install -y iproute
	    [[ $(command -v sudo) ]] || dnf install -y sudo

	    printf "%s\n" "${GREEN}dnf ${YELLOW}install -y --skip-broken ${BLUE}dnf-utils passwd findutils man-db glibc-all-langpacks${RESET}"
	    if [[ ${WEEKLY_BUILD_CONTAINER} != true ]]; then
	        dnf install -y --skip-broken dnf-utils passwd findutils man-db glibc-all-langpacks || yum install -y --skip-broken dnf-utils passwd findutils man-db glibc-all-langpacks
	    fi
	    if [[ ! $(command -v pkill) ]]; then
	        printf "%s\n" "${GREEN}dnf ${YELLOW}install -y ${PURPLE}--skip-broken ${BLUE}procps-ng procps-ng-i18n${RESET}"
	        dnf install -y --skip-broken procps-ng procps-ng-i18n
	    fi
	    #TMOE_LANG_HALF=$(printf '%s\n' "${LANG}" | cut -d '.' -f 1 |cut -d '_' -f 1)
	    #glibc-all-langpacks
	    #dnf install -y --skip-broken glibc-minimal-langpack.aarch64 "glibc-langpack-${TMOE_LANG_QUATER}*"
	    [[ $(command -v whiptail) ]] || dnf install --skip-broken -y newt
	elif grep -Eq 'CentOS|Rocky Linux|rhel' /etc/os-release; then
	    [[ ! -e /etc/yum.repos.d/CentOS-Base.repo ]] || cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak
	    #curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-8.repo
	    #curl -Lo /etc/yum.repos.d/CentOS-Base.repo https://mirrors.huaweicloud.com/repository/conf/CentOS-8-anon.repo
	    [[ $(command -v dnf) ]] || yum install -y dnf
	    [[ $(command -v dnf) ]] || ln -svf $(command -v yum) /usr/bin/dnf
	    printf "%s\n" "${GREEN}dnf ${YELLOW}install -y ${PURPLE}--skip-broken ${BLUE}epel-release${RESET}"
	    yes | dnf install -y --skip-broken epel-release

	    printf "%s\n" "${GREEN}dnf ${YELLOW}install -y --skip-broken ${BLUE}dnf-utils glibc-langpack-${TMOE_LANG_QUATER}*${RESET}"
	    dnf install -y dnf-utils "glibc-langpack-${TMOE_LANG_QUATER}*" || yum install -y --skip-broken dnf-utils glibc-all-langpacks
		export LANG=${TMOE_LANG}

	    for i in hostname sudo; do
	        if [[ ! $(command -v ${i}) ]]; then
	            printf "%s\n" "${GREEN}dnf ${YELLOW}install -y ${PURPLE}--skip-broken ${BLUE}${i}${RESET}"
	            dnf install -y --skip-broken ${i}
	        fi
	    done
	    [[ $(command -v whiptail) ]] || yum install --skip-broken -y newt
	fi
	############################
	printf "%s\n" "Automatically configure zsh after 2 seconds,you can press Ctrl + C to cancel."
	#printf "%s\n" "2s后将自动开始配置zsh，您可以按Ctrl+C取消，这将不会继续配置其它步骤，同时也不会启动Tmoe-linux工具。"
	################
	################
	slackware_mirror_list() {
	    LINUX_DISTRO='slackware'
	    sed -i 's/^ftp/#&/g' /etc/slackpkg/mirrors
	    sed -i 's/^http/#&/g' /etc/slackpkg/mirrors
	    sed -i '$ a\https://mirrors.bfsu.edu.cn/slackwarearm/slackwarearm-current/' /etc/slackpkg/mirrors
	    cat /etc/slackpkg/mirrors
	    slackpkg update gpg
	    slackpkg update
	}
	###################
	if [ "$(grep 'ID=' /etc/os-release | head -n 1 | cut -d '=' -f 2)" = "slackware" ]; then
	    slackware_mirror_list
	    slackpkg install newt
	fi
	note_of_non_debian() {
	    case ${TMOE_LANG} in
	    zh_*UTF-8) printf "%s\n" "您可以输${GREEN}debian-i${RESET}或${YELLOW}tmoe t${RESET}来打开软件安装工具" ;;
	    *) ;;
	    esac
	    printf "%s\n" "You can type ${GREEN}debian-i${RESET} or ${YELLOW}tmoe t${RESET} to start ${BLUE}tmoe tools.${RESET}"
	    bash zsh.sh
	}
	################
	if ! grep -Eq 'debian|ubuntu' '/etc/os-release'; then
	    note_of_non_debian
	else
	    bash zsh.sh
	fi
ENDOFbashPROFILE
#cp .profile .zlogin
printf "%s\n" "bash ~/.profile" >.zlogin
#${TMOE_CHROOT_PREFIX} mv -vf ${DEBIAN_CHROOT}/usr/bin/zsh ${DEBIAN_CHROOT}/usr/bin/zsh-01
#${TMOE_CHROOT_PREFIX} mv -vf ${DEBIAN_CHROOT}/bin/zsh ${DEBIAN_CHROOT}/usr/bin/zsh-01
#####################
case ${TMOE_CHROOT} in
true)
    ${TMOE_CHROOT_PREFIX} rm -f "${DEBIAN_CHROOT}"/root/.bash_profile "${DEBIAN_CHROOT}"/root/.bash_login
    ${TMOE_CHROOT_PREFIX} mv "${DEBIAN_CHROOT}"/root/.profile "${DEBIAN_CHROOT}"/root/.profile.bak 2>/dev/null
    ${TMOE_CHROOT_PREFIX} cp .profile .zlogin "${DEBIAN_CHROOT}"/root
    ;;
esac
#sed -i '1 r vnc-autostartup' ./.bash_login
#####################
check_current_user_name_and_group() {
    CURRENT_USER_NAME=$(grep "${HOME}" /etc/passwd | awk -F ':' '{print $1}')
    CURRENT_USER_GROUP=$(grep "${HOME}" /etc/passwd | awk -F ':' '{print $4}' | cut -d ',' -f 1 | head -n 1)
    if [ -z "${CURRENT_USER_GROUP}" ]; then
        CURRENT_USER_GROUP=${CURRENT_USER_NAME}
    fi
}
#################
#if [ "${LINUX_DISTRO}" != 'Android' ]; then
# sed -i 's:#!/usr/bin/env bash:#!/usr/bin/env bash:g' $(grep -rl 'com.termux' "${PREFIX}/bin")
#sed -i 's:#!/usr/bin/env bash:#!/usr/bin/env bash:' ${DEBIAN_CHROOT}/remove-debian.sh
#fi
case ${TMOE_CHROOT} in
true) ;;
#su -c "chown -Rv 0:0 ${DEBIAN_CHROOT}"
*)
    case ${LINUX_DISTRO} in
    Android) ;;
    *)
        check_current_user_name_and_group
        case ${HOME} in
        /root) ;;
        *)
            chown -Rv "${CURRENT_USER_NAME}:${CURRENT_USER_GROUP}" "${DEBIAN_CHROOT}"
            su - "${CURRENT_USER_NAME}" -c "bash ${PREFIX}/bin/debian"
            exit 0
            ;;
        esac
        ;;
    esac
    ;;
esac
bash ${PREFIX}/bin/debian #此处不应以sudo权限执行

###########
